mirror of
https://github.com/bitbaum/loki.git
synced 2026-12-04 09:47:22 +01:00
User asked: stop firing auto-inject prompts while the agent is mid-task;
inject should only fire when the agent has done everything and now
needs a nudge. They also called out the broader goal that this should
work for any model (claude, codex, gemini, openclaw, or future
adapters) — not just claude — since today's behavior is implicitly
claude-coupled through ~/.claude/sessions/*.md and the stop hook.
Added a new \`status\` field to the canonical handoff format. The
agent self-reports lifecycle state per turn:
status: ready — task fully done, auto-inject may proceed
status: working — agent is mid-task, suppress auto-inject
Missing / undefined / any-other-value is treated as NOT ready. This
inverts today's implicit default (auto-fire fires on every turn end)
so the agent must explicitly signal it's done with everything before
the beacon/ReadyBanner countdown fires the next prompt. Matches the
user's stated intent literally.
Why this is model-agnostic: the field lives in the canonical
ORCHESTRATION_TASK_SUMMARY_FIELDS constant that ALL adapters' handoff
templates read from (claude via buildPromptWithSession, openclaw via
renderSharedHandoffBlock, codex/gemini will inherit when their
handoff plumbing is wired). The parsers (parseSessionFile,
parseSessionText, home/watcher.ts:parseHandoff) all pick it up
automatically. Any new adapter that writes the standard handoff
format gets the same gating.
Files touched:
• src/lib/orchestration/contract.ts — added 'status' to
ORCHESTRATION_TASK_SUMMARY_FIELDS; OrchestrationTaskSummary makes
status optional for back-compat.
• src/lib/events.ts — Handoff zod schema gains status (defaults to
"") so home/ events with status round-trip cleanly.
• src/lib/control-types.ts — SessionState.status is optional;
legacy construction sites that don't yet plumb session_status can
omit it and naturally suppress auto-fire.
• src/lib/agent-config.ts:buildPromptWithSession — new status line
in the handoff template prose (the one claude reads each turn).
• src/lib/orchestration/renderers.ts:renderSharedHandoffBlock —
same line for openclaw.
• src/lib/session-content.ts:parseSessionText — beacon DB parser
extracts status.
• home/watcher.ts:FIELDS — home/ watcher's handoff parser includes
status (cascades to worker.idle events).
• src/hooks/use-project-card-actions.ts:handleAutoInject —
explicit gate: only fires when status === 'ready' (or
health-critical for recovery dispatches).
• src/app/beacon/[id]/BeaconClient.tsx:handleAutoInject — same
gate, parsing status out of session.sessionContent via
parseSessionText (BeaconSession carries raw md text).
• src/app/api/orchestration/runs/[id]/finish/route.ts — finish
body summary preserves status.
• home/{decide,emit,state,worker}.ts test fixtures — added
status: "" to all Handoff literals so the new required-after-
default field type-checks.
tsc clean, eslint clean, npm run test:home 82/82.
Transition note: until adapters start emitting status in their
handoffs, auto-inject will suppress for everyone. This is the user's
explicit choice ("only fire when the agent has done everything").
The handoff template prose now tells the agent to write the field,
so going forward agents will include it.
NOT shipped in this commit (deliberate scope cut, queued for next):
• DB column session_status on project_states (mirror of the new
field) — without it, control/stream/route.ts can't surface the
field server-side. Today the BeaconClient parses status directly
from raw session.md content; the broader cloud /control flow
will get accurate status once the column lands.
• Bash side (agent-hook-bridge.sh:emit_worker_finished) reading
status from session.md and including in worker.finished events.
The user has denied prior edits to that file; happy to ship if
they want or leave it for them to land.
157 lines
6.3 KiB
TypeScript
157 lines
6.3 KiB
TypeScript
/**
|
|
* Append an event to the JSONL log.
|
|
*
|
|
* The single write-side counterpart to log.ts (which reads). Used by:
|
|
* - home/watcher.ts when an agent stop-hook signals worker.idle
|
|
* - home/server.ts:/api/events for manual testing
|
|
* - future M6 dispatch path (brain → bridge.dispatch → log → worker)
|
|
*
|
|
* Writes are append-only. We never rewrite or truncate the log here — the
|
|
* worst case a corrupted line can do is fail to parse on the read side,
|
|
* which log.ts handles via its parseEvent error path.
|
|
*/
|
|
|
|
import fs from "node:fs";
|
|
import path from "node:path";
|
|
import os from "node:os";
|
|
import { randomUUID } from "node:crypto";
|
|
import { APP_SLUG } from "@/config/brand";
|
|
import { EVENT_VERSION, parseEvent, serializeEvent, type Event } from "@/lib/events";
|
|
|
|
export const LOG_PATH = path.join(os.homedir(), `.${APP_SLUG}`, "events.jsonl");
|
|
|
|
/**
|
|
* Common envelope fields. Stamps id + ts + v at append time.
|
|
*
|
|
* Distributive Omit via a generic parameter — native `Omit<Event, K>` keeps
|
|
* the union as one shape and drops kind-specific fields like `handoff`. The
|
|
* generic indirection (T extends unknown) is the canonical TS trick to make
|
|
* the omit apply per-variant so each kind keeps its own fields.
|
|
*/
|
|
type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;
|
|
type EventPayload = DistributiveOmit<Event, "id" | "ts" | "v">;
|
|
|
|
export function appendEvent(payload: EventPayload, logPath: string = LOG_PATH): Event {
|
|
fs.mkdirSync(path.dirname(logPath), { recursive: true });
|
|
const event = {
|
|
v: EVENT_VERSION,
|
|
id: randomUUID(),
|
|
ts: new Date().toISOString(),
|
|
...payload,
|
|
} as Event;
|
|
fs.appendFileSync(logPath, serializeEvent(event));
|
|
// Return the stamped event so callers can eagerly project it into their
|
|
// own state without waiting for tailLog to consume the write. Closes a
|
|
// race in server.ts's /api/dispatch where back-to-back concurrent
|
|
// requests both read pre-dispatch state because fs.watch hadn't fired
|
|
// yet.
|
|
return event;
|
|
}
|
|
|
|
// ── Self-test ────────────────────────────────────────────────────────────────
|
|
// Run with: npx tsx home/emit.ts --self-test
|
|
// Writes to a unique temp file (NOT the real log) so production state isn't
|
|
// touched. Round-trips through parseEvent to verify the wire format holds.
|
|
|
|
function selfTest() {
|
|
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), `${APP_SLUG}-emit-test-`));
|
|
const tmpLog = path.join(tmpDir, "events.jsonl");
|
|
|
|
type Case = { name: string; run: () => boolean };
|
|
const cases: Case[] = [
|
|
{
|
|
name: "appendEvent stamps v, id, ts and round-trips via parseEvent",
|
|
run: () => {
|
|
appendEvent({
|
|
kind: "worker.idle",
|
|
project: "TestProject",
|
|
handoff: { status: "", done:"", next: "", tests: "", todos: "", health: "good" },
|
|
}, tmpLog);
|
|
const line = fs.readFileSync(tmpLog, "utf8").trim();
|
|
const parsed = parseEvent(line);
|
|
if (!parsed.ok) return false;
|
|
return parsed.event.v === EVENT_VERSION
|
|
&& typeof parsed.event.id === "string"
|
|
&& parsed.event.id.length === 36 // UUID
|
|
&& parsed.event.ts.endsWith("Z") // ISO 8601
|
|
&& parsed.event.kind === "worker.idle"
|
|
&& parsed.event.project === "TestProject";
|
|
},
|
|
},
|
|
{
|
|
name: "two consecutive appends produce distinct ids",
|
|
run: () => {
|
|
const log = path.join(tmpDir, "distinct.jsonl");
|
|
appendEvent({ kind: "worker.idle", project: "A",
|
|
handoff: { status: "", done:"", next: "", tests: "", todos: "", health: "" }}, log);
|
|
appendEvent({ kind: "worker.idle", project: "A",
|
|
handoff: { status: "", done:"", next: "", tests: "", todos: "", health: "" }}, log);
|
|
const lines = fs.readFileSync(log, "utf8").trim().split("\n");
|
|
if (lines.length !== 2) return false;
|
|
const r1 = parseEvent(lines[0]); const r2 = parseEvent(lines[1]);
|
|
return r1.ok && r2.ok && r1.event.id !== r2.event.id;
|
|
},
|
|
},
|
|
{
|
|
name: "appendEvent creates the parent directory if missing",
|
|
run: () => {
|
|
const nested = path.join(tmpDir, "deeply/nested/path/log.jsonl");
|
|
appendEvent({ kind: "worker.idle", project: "Nest",
|
|
handoff: { status: "", done:"", next: "", tests: "", todos: "", health: "" }}, nested);
|
|
return fs.existsSync(nested) && fs.statSync(nested).size > 0;
|
|
},
|
|
},
|
|
{
|
|
name: "bridge.dispatch payload preserves kind-specific fields (DistributiveOmit sanity check)",
|
|
run: () => {
|
|
const log = path.join(tmpDir, "dispatch.jsonl");
|
|
appendEvent({
|
|
kind: "bridge.dispatch",
|
|
project: "X",
|
|
intent: "next_best",
|
|
prompt: "go",
|
|
runId: "550e8400-e29b-41d4-a716-446655440000",
|
|
autonomy: "manual",
|
|
reason: "test",
|
|
confidence: 0.8,
|
|
}, log);
|
|
const parsed = parseEvent(fs.readFileSync(log, "utf8").trim());
|
|
if (!parsed.ok || parsed.event.kind !== "bridge.dispatch") return false;
|
|
return parsed.event.prompt === "go"
|
|
&& parsed.event.autonomy === "manual"
|
|
&& parsed.event.confidence === 0.8;
|
|
},
|
|
},
|
|
{
|
|
name: "worker.crashed payload preserves the error message",
|
|
run: () => {
|
|
const log = path.join(tmpDir, "crashed.jsonl");
|
|
appendEvent({
|
|
kind: "worker.crashed",
|
|
project: "X",
|
|
runId: "550e8400-e29b-41d4-a716-446655440000",
|
|
error: "inject failed: tab not found",
|
|
}, log);
|
|
const parsed = parseEvent(fs.readFileSync(log, "utf8").trim());
|
|
return parsed.ok
|
|
&& parsed.event.kind === "worker.crashed"
|
|
&& parsed.event.error === "inject failed: tab not found";
|
|
},
|
|
},
|
|
];
|
|
|
|
let pass = 0, fail = 0;
|
|
for (const c of cases) {
|
|
if (c.run()) { console.log(` ✓ ${c.name}`); pass++; }
|
|
else { console.log(` ✗ ${c.name}`); fail++; }
|
|
}
|
|
// Clean up the temp tree even on assertion failure.
|
|
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
console.log(`\n${pass}/${pass + fail} passed`);
|
|
if (fail > 0) process.exit(1);
|
|
}
|
|
|
|
if (import.meta.url === `file://${process.argv[1]}`) {
|
|
if (process.argv.includes("--self-test")) selfTest();
|
|
}
|