Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(daemon,community): richer bot audit rows + local-tz timestamps for agents

Guse089a5b49b87
diff --git a/src/daemon/src/cli/index.test.ts b/src/daemon/src/cli/index.test.ts
index 33cfb7bfe..1ec0ee1b2 100644
--- a/src/daemon/src/cli/index.test.ts
+++ b/src/daemon/src/cli/index.test.ts
@@ -117,10 +117,13 @@ describe("inbox pull", () => {
}),
);
await main(["inbox", "pull"]);
- const env = parseEnvelope(cap.lines()) as { success: { acked: number; messages: unknown[] } };
+ const env = parseEnvelope(cap.lines()) as {
+ success: { acked: number; messages: unknown[]; pulledAt: string };
+ };
expect(ackSpy).toHaveBeenCalledOnce();
expect(env.success.acked).toBe(1);
expect(env.success.messages).toHaveLength(1);
+ expect(env.success.pulledAt).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}[+-]\d{2}:\d{2}$/);
});
it("--no-ack skips advancing the waterline", async () => {
diff --git a/src/daemon/src/cli/index.ts b/src/daemon/src/cli/index.ts
index b1aeb50d5..d6db609c3 100755
--- a/src/daemon/src/cli/index.ts
+++ b/src/daemon/src/cli/index.ts
@@ -19,6 +19,16 @@ import type { ServerApi, Cursor, Message } from "../server/contract.js";
import { proxyServerApiFromEnv } from "./proxyServerApi.js";
import { daemonStart, daemonStop, daemonList } from "./daemonStart.js";
import { parseInviteToken } from "@alook/shared/lib/invite-link";
+import { nowLocalISO, toLocalISO } from "../util/localTime.js";
+
+/**
+ * Rewrite every message's UTC `.time` (server-stamped) into local-tz ISO with
+ * offset, so the agent sees timestamps in its own timezone throughout the CLI
+ * envelope. Server truth stays untouched — we only reformat at the boundary.
+ */
+function messagesInLocalTime(messages: Message[]): Message[] {
+ return messages.map((m) => ({ ...m, time: toLocalISO(m.time) }));
+}
/** The mandatory output envelope. Null/undefined fields are stripped on print. */
interface Envelope {
@@ -217,6 +227,7 @@ async function cmdInboxPull(opts: Record<string, unknown>): Promise<unknown> {
const agent = agentId(opts);
const max = opts.max ? Number(opts.max) : undefined;
const { messages, hasMore } = await api.inboxPull({ agentId: agent, max });
+ const pulledAt = nowLocalISO();
let acked = 0;
if (opts.ack !== false && messages.length > 0) {
@@ -230,7 +241,7 @@ async function cmdInboxPull(opts: Record<string, unknown>): Promise<unknown> {
acked = latest.size;
}
- return { messages: messages as Message[], hasMore, acked };
+ return { messages: messagesInLocalTime(messages), hasMore, acked, pulledAt };
}
async function cmdServerList(opts: Record<string, unknown>): Promise<unknown> {
@@ -290,7 +301,7 @@ async function cmdChannelHistory(opts: Record<string, unknown>): Promise<unknown
around: toSeq(opts.around),
limit: toSeq(opts.limit),
});
- return { items, hasMore, ...(latestSeq !== undefined ? { latestSeq } : {}) };
+ return { items: messagesInLocalTime(items), hasMore, ...(latestSeq !== undefined ? { latestSeq } : {}) };
}
/* ------------------------------------------------------------------ */
diff --git a/src/daemon/src/daemon/createDaemon.test.ts b/src/daemon/src/daemon/createDaemon.test.ts
index 1c89b2589..71e81715e 100644
--- a/src/daemon/src/daemon/createDaemon.test.ts
+++ b/src/daemon/src/daemon/createDaemon.test.ts
@@ -1,6 +1,6 @@
import { describe, it, expect, vi, afterEach } from "vitest";
import { EventEmitter } from "events";
-import { createDaemon, deriveAuditLogSubcommand } from "./createDaemon";
+import { createDaemon, deriveAuditLogSubcommand, emitImplicitTypingStopOnSend } from "./createDaemon";
import type { Driver } from "../types";
import type { Logger } from "../logger";
@@ -457,6 +457,61 @@ describe("deriveAuditLogSubcommand", () => {
});
});
+describe("emitImplicitTypingStopOnSend", () => {
+ const tracker = (scopes: Record<string, string[]>) => ({
+ snapshot: (agentId: string) => scopes[agentId] ?? [],
+ });
+
+ it("emits an agent_typing_stop for every active DM scope when the sub is `send`", () => {
+ const emitted: Array<{ agentId: string; dmConversationId: string }> = [];
+ emitImplicitTypingStopOnSend({
+ subcommand: "send",
+ agentId: "bot_1",
+ typingTracker: tracker({ bot_1: ["dm-a", "dm-b"] }),
+ reportAgentTypingStop: (info) => emitted.push(info),
+ });
+ expect(emitted).toEqual([
+ { agentId: "bot_1", dmConversationId: "dm-a" },
+ { agentId: "bot_1", dmConversationId: "dm-b" },
+ ]);
+ });
+
+ it("no-ops when the sub is not `send`", () => {
+ const emitted: unknown[] = [];
+ for (const sub of ["inboxPull", "read", "listServers", "attachmentUpload"]) {
+ emitImplicitTypingStopOnSend({
+ subcommand: sub,
+ agentId: "bot_1",
+ typingTracker: tracker({ bot_1: ["dm-a"] }),
+ reportAgentTypingStop: (info) => emitted.push(info),
+ });
+ }
+ expect(emitted).toEqual([]);
+ });
+
+ it("no-ops when the tracker has no scope for this agent (never woken via DM)", () => {
+ const emitted: unknown[] = [];
+ emitImplicitTypingStopOnSend({
+ subcommand: "send",
+ agentId: "bot_1",
+ typingTracker: tracker({}),
+ reportAgentTypingStop: (info) => emitted.push(info),
+ });
+ expect(emitted).toEqual([]);
+ });
+
+ it("no-ops when the channel isn't wired for typing (defensive)", () => {
+ expect(() =>
+ emitImplicitTypingStopOnSend({
+ subcommand: "send",
+ agentId: "bot_1",
+ typingTracker: tracker({ bot_1: ["dm-a"] }),
+ reportAgentTypingStop: undefined,
+ }),
+ ).not.toThrow();
+ });
+});
+
describe("AgentProcessManager.auditContext", () => {
// Producer B (credential-proxy sighting) reads this so `cli_invocation`
// rows carry the same context Producer A's tool_call / thinking rows do.
diff --git a/src/daemon/src/daemon/createDaemon.ts b/src/daemon/src/daemon/createDaemon.ts
index e0e8c488e..315956708 100644
--- a/src/daemon/src/daemon/createDaemon.ts
+++ b/src/daemon/src/daemon/createDaemon.ts
@@ -61,6 +61,34 @@ export function deriveAuditLogSubcommand(pathname: string): string | null {
return sub;
}
+/**
+ * Implicit typing.stop on `alook message send`. Emits `agent_typing_stop` for
+ * every DM scope currently tracked for the agent, and DELIBERATELY leaves the
+ * `typingTracker` + heartbeat interval untouched. Semantics:
+ * - Client pill drops immediately (nice UX when the reply just landed).
+ * - If the agent is still working, the next scheduled `agent_typing` frame
+ * (≤5s later, from the heartbeat) re-arms the pill.
+ * - If `turn_end` follows shortly, the normal FSM path (`onAgentActivity` →
+ * `emitTypingStopsAndClear`) clears the tracker and stops the heartbeat,
+ * so the pill stays down.
+ * Guards a driver stream that never emits `turn_end` (a known Claude Code
+ * failure mode: `type:"result"` never lands, `turnActive` stays `true`
+ * forever, pill would dangle without this fallback).
+ */
+export function emitImplicitTypingStopOnSend(args: {
+ subcommand: string;
+ agentId: string;
+ typingTracker: Pick<TypingScopeTracker, "snapshot">;
+ reportAgentTypingStop?: (info: { agentId: string; dmConversationId: string }) => void;
+}): void {
+ if (args.subcommand !== "send") return;
+ const emit = args.reportAgentTypingStop;
+ if (!emit) return;
+ for (const dmConversationId of args.typingTracker.snapshot(args.agentId)) {
+ emit({ agentId: args.agentId, dmConversationId });
+ }
+}
+
/** The minimal WebSocket the control channel needs (host injects a `ws` factory). */
export type DaemonWebSocketFactory = (url: string, headers: Record<string, string>) => unknown;
@@ -153,7 +181,7 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
agentId: string,
event:
| { kind: "cli_invocation"; payload: { subcommand: string } }
- | { kind: "tool_call"; payload: { name: string } }
+ | { kind: "tool_call"; payload: { name: string; command?: string } }
| { kind: "thinking"; payload: { text: string; truncated: boolean; chars: number } },
context?: { sessionId?: string | null; launchId?: string | null }
) => {
@@ -166,6 +194,10 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
});
};
+ // Declared above the proxy so `onProxyRequest`'s implicit-typing.stop hook
+ // can read it. Populated later by the AgentRouter on each `agent:wake`.
+ const typingTracker: TypingScopeTracker = createTypingScopeTracker();
+
const broker = new CredentialBroker({ upstreamBaseUrl: opts.serverUrl });
const proxy = await startCredentialProxy(broker, {
onInboxPullResponse: (agentId, messages) => timeline.appendEntryForAgent(agentId, messages),
@@ -182,6 +214,13 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
kind: "cli_invocation",
payload: { subcommand },
}, context);
+ // Typing pill fallback — see `emitImplicitTypingStopOnSend` docstring.
+ emitImplicitTypingStopOnSend({
+ subcommand,
+ agentId,
+ typingTracker,
+ reportAgentTypingStop: channelRef?.reportAgentTypingStop?.bind(channelRef),
+ });
},
});
@@ -190,11 +229,11 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
// ── Bot typing indicator (DM-only) ─────────────────────────────────────
//
- // Shared in-memory tracker of per-agent DM conversation ids the daemon
- // should be broadcasting "bot is typing…" for. Populated by the
- // AgentRouter on each `agent:wake` (from `unreadNotice.dmConversationId`)
- // and cleared on FSM transitions into `idle`/`stopping`.
- const typingTracker: TypingScopeTracker = createTypingScopeTracker();
+ // `typingTracker` is declared above the proxy so `onProxyRequest`'s
+ // implicit-typing.stop hook can read it. Populated by the AgentRouter on
+ // each `agent:wake` (from `unreadNotice.dmConversationId`) and cleared on
+ // FSM transitions into `idle`/`stopping`.
+ //
// Per-agent heartbeat interval handles. Only alive while an agent is in
// a running-family state; recreated on each starting/running transition.
const typingHeartbeats = new Map<string, ReturnType<typeof setInterval>>();
@@ -507,6 +546,7 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
sdkDriverDepsFor: (ctx) => createPiSdkDriverDeps(ctx),
timeline,
wakePromptFooter: "Use `alook inbox pull` to read your messages, then reply with `alook message send`.",
+ stampWakePromptTime: true,
logger: log.child("manager"),
});
managerRef = manager;
diff --git a/src/daemon/src/manager/managerRuntime.test.ts b/src/daemon/src/manager/managerRuntime.test.ts
index 4df53da20..cbb00e773 100644
--- a/src/daemon/src/manager/managerRuntime.test.ts
+++ b/src/daemon/src/manager/managerRuntime.test.ts
@@ -1,5 +1,12 @@
import { describe, it, expect, vi } from "vitest";
-import { AgentProcessManager, truncateThinking, type ManagedSession, type SessionFactory } from "./managerRuntime.js";
+import {
+ AgentProcessManager,
+ truncateThinking,
+ extractBashCommandSummary,
+ isAlookShellCommand,
+ type ManagedSession,
+ type SessionFactory,
+} from "./managerRuntime.js";
import { SdkRuntimeSession, type SdkSessionHandle } from "../runtime/sdkRuntimeSession.js";
import type { Driver, LaunchContext, SdkDriverDeps } from "../types.js";
import type { Logger } from "../logger.js";
@@ -848,23 +855,109 @@ describe("AgentProcessManager — bot audit event emission", () => {
);
});
- it("DROPS `tool_call { name: \"Bash\" }` regardless of proxy sightings (Bash suppression)", () => {
+ it("DROPS `Bash` tool_call whose command is `alook <sub>` (proxy is authoritative)", () => {
const onBotAuditEvent = vi.fn();
const { mgr, session } = makeManager({ onBotAuditEvent });
mgr.deliver("a1", { seq: 1, text: "hello" });
- session.fire("runtime_event", { kind: "tool_call", name: "Bash", input: { command: "ls -la" } });
+ session.fire("runtime_event", {
+ kind: "tool_call",
+ name: "Bash",
+ input: { command: "alook inbox pull --max 5" },
+ });
+ session.fire("runtime_event", {
+ kind: "tool_call",
+ name: "Bash",
+ input: { command: " alook message send @gus hi" },
+ });
+ session.fire("runtime_event", {
+ kind: "tool_call",
+ name: "Bash",
+ input: { command: "alook" },
+ });
- // No audit event should be emitted for a Bash tool_call — the
- // credential-proxy sighting (Producer B) is the authoritative source
- // for `alook <sub>` invocations. Non-audit-hook side effects (progress
- // dispatch) are unaffected.
const bashCalls = onBotAuditEvent.mock.calls.filter(
([, ev]) => (ev as { kind?: string })?.kind === "tool_call"
);
expect(bashCalls).toHaveLength(0);
});
+ it("EMITS `Bash` tool_call for non-alook shell work (rm, sed, git, echo)", () => {
+ const onBotAuditEvent = vi.fn();
+ const { mgr, session } = makeManager({ onBotAuditEvent });
+ mgr.deliver("a1", { seq: 1, text: "hello" });
+
+ session.fire("runtime_event", {
+ kind: "tool_call",
+ name: "Bash",
+ input: { command: "rm -rf /tmp/xxx" },
+ });
+ session.fire("runtime_event", {
+ kind: "tool_call",
+ name: "Bash",
+ input: { command: "sed -i '' '/pattern/d' todo.md" },
+ });
+ session.fire("runtime_event", {
+ kind: "tool_call",
+ name: "Bash",
+ input: { command: "echo -n > todo.md" },
+ });
+
+ const bashCalls = onBotAuditEvent.mock.calls.filter(
+ ([, ev]) => (ev as { kind?: string })?.kind === "tool_call"
+ );
+ expect(bashCalls).toHaveLength(3);
+ expect((bashCalls[0]![1] as { payload: { command?: string } }).payload.command).toBe("rm -rf /tmp/xxx");
+ expect((bashCalls[1]![1] as { payload: { command?: string } }).payload.command).toBe(
+ "sed -i '' '/pattern/d' todo.md",
+ );
+ expect((bashCalls[2]![1] as { payload: { command?: string } }).payload.command).toBe("echo -n > todo.md");
+ });
+
+ it("truncates a long Bash command to <= 200 chars with an ellipsis", () => {
+ const onBotAuditEvent = vi.fn();
+ const { mgr, session } = makeManager({ onBotAuditEvent });
+ mgr.deliver("a1", { seq: 1, text: "hello" });
+
+ const long = "echo " + "x".repeat(400);
+ session.fire("runtime_event", { kind: "tool_call", name: "Bash", input: { command: long } });
+
+ const [call] = onBotAuditEvent.mock.calls.filter(
+ ([, ev]) => (ev as { kind?: string })?.kind === "tool_call",
+ );
+ const cmd = (call![1] as { payload: { command?: string } }).payload.command!;
+ expect([...cmd].length).toBeLessThanOrEqual(200);
+ expect(cmd.endsWith("…")).toBe(true);
+ });
+
+ it("emits a `Bash` tool_call without `command` when input has no command string", () => {
+ const onBotAuditEvent = vi.fn();
+ const { mgr, session } = makeManager({ onBotAuditEvent });
+ mgr.deliver("a1", { seq: 1, text: "hello" });
+
+ session.fire("runtime_event", { kind: "tool_call", name: "Bash", input: {} });
+
+ const [call] = onBotAuditEvent.mock.calls.filter(
+ ([, ev]) => (ev as { kind?: string })?.kind === "tool_call",
+ );
+ expect((call![1] as { payload: unknown }).payload).toEqual({ name: "Bash" });
+ });
+
+ it("emits non-Bash tool_calls (Edit, Write, MultiEdit, Grep, Glob) with name only", () => {
+ const onBotAuditEvent = vi.fn();
+ const { mgr, session } = makeManager({ onBotAuditEvent });
+ mgr.deliver("a1", { seq: 1, text: "hello" });
+
+ for (const name of ["Edit", "Write", "MultiEdit", "Grep", "Glob"]) {
+ session.fire("runtime_event", { kind: "tool_call", name, input: { path: "/x" } });
+ }
+
+ const names = onBotAuditEvent.mock.calls
+ .filter(([, ev]) => (ev as { kind?: string })?.kind === "tool_call")
+ .map(([, ev]) => (ev as { payload: { name: string } }).payload.name);
+ expect(names).toEqual(["Edit", "Write", "MultiEdit", "Grep", "Glob"]);
+ });
+
it("does NOT emit for non-audit event kinds (session_init, text, turn_end)", () => {
const onBotAuditEvent = vi.fn();
const { mgr, session } = makeManager({ onBotAuditEvent });
@@ -877,3 +970,57 @@ describe("AgentProcessManager — bot audit event emission", () => {
expect(onBotAuditEvent).not.toHaveBeenCalled();
});
});
+
+describe("extractBashCommandSummary", () => {
+ it("returns the command verbatim when it fits", () => {
+ expect(extractBashCommandSummary({ command: "rm -rf tmp" })).toBe("rm -rf tmp");
+ });
+
+ it("returns the first non-empty line", () => {
+ expect(extractBashCommandSummary({ command: "\n\n git commit -m 'wip' \nfoo" })).toBe(
+ "git commit -m 'wip'",
+ );
+ });
+
+ it("handles codex-shaped `input.item.command` string", () => {
+ expect(extractBashCommandSummary({ item: { command: "ls -la" } })).toBe("ls -la");
+ });
+
+ it("handles codex-shaped `input.item.command` array", () => {
+ expect(extractBashCommandSummary({ item: { command: ["bash", "-lc", "echo hi"] } })).toBe(
+ "bash -lc echo hi",
+ );
+ });
+
+ it("returns undefined when no command string is present", () => {
+ expect(extractBashCommandSummary({})).toBeUndefined();
+ expect(extractBashCommandSummary(null)).toBeUndefined();
+ expect(extractBashCommandSummary({ item: {} })).toBeUndefined();
+ });
+
+ it("truncates to <=200 chars with an ellipsis", () => {
+ const long = "echo " + "y".repeat(400);
+ const out = extractBashCommandSummary({ command: long })!;
+ expect([...out].length).toBeLessThanOrEqual(200);
+ expect(out.endsWith("…")).toBe(true);
+ });
+});
+
+describe("isAlookShellCommand", () => {
+ it("matches `alook <sub>` and bare `alook`", () => {
+ expect(isAlookShellCommand("alook")).toBe(true);
+ expect(isAlookShellCommand("alook inbox pull")).toBe(true);
+ expect(isAlookShellCommand(" alook message send")).toBe(true);
+ });
+
+ it("does NOT match commands that merely mention alook", () => {
+ expect(isAlookShellCommand("rm alook.log")).toBe(false);
+ expect(isAlookShellCommand("echo alook")).toBe(false);
+ expect(isAlookShellCommand("alookalike")).toBe(false);
+ });
+
+ it("returns false for missing input", () => {
+ expect(isAlookShellCommand(undefined)).toBe(false);
+ expect(isAlookShellCommand("")).toBe(false);
+ });
+});
diff --git a/src/daemon/src/manager/managerRuntime.ts b/src/daemon/src/manager/managerRuntime.ts
index 24b0b5867..19a48f144 100644
--- a/src/daemon/src/manager/managerRuntime.ts
+++ b/src/daemon/src/manager/managerRuntime.ts
@@ -25,6 +25,7 @@ import type { RuntimeConfig } from "../runtimeConfig.js";
import { createChildProcessRuntimeSession, type ChildProcessRuntimeSession } from "../runtime/runtimeSession.js";
import { SdkManagedSession } from "../runtime/sdkManagedSession.js";
import { createLogger, type Logger } from "../logger.js";
+import { nowLocalISO } from "../util/localTime.js";
/**
* Derived activity state reported up the control plane — NOT a raw passthrough
@@ -99,18 +100,20 @@ export interface ManagerRuntimeOpts {
*/
onAgentActivity?: (info: { agentId: string; state: AgentActivityState }) => void;
/**
- * Notified whenever a runtime `thinking` or non-`Bash` `tool_call` event
- * lands. Wired in `createDaemon` to send a `bot_audit_event` frame through
- * the WS control channel. Not called for `Bash` tool_calls — see the
- * "Bash suppression" branch inside `onRuntimeEvent`.
+ * Notified whenever a runtime `thinking` or `tool_call` event lands. Wired
+ * in `createDaemon` to send a `bot_audit_event` frame through the WS
+ * control channel. `Bash` tool_calls whose `input.command` starts with
+ * `alook ` are dropped inside `onRuntimeEvent` — the credential-proxy
+ * `cli_invocation` sighting is authoritative for those. Every other `Bash`
+ * call arrives here with a truncated `command` summary attached.
*
- * Kept minimal on purpose: no `input`, no output — the audit log records
- * NAME only for tool_calls, and truncated `text` for thinking.
+ * `thinking` payloads carry truncated `text` + original `chars`; the audit
+ * log does not record raw tool input beyond the optional `command`.
*/
onBotAuditEvent?: (
agentId: string,
event:
- | { kind: "tool_call"; payload: { name: string } }
+ | { kind: "tool_call"; payload: { name: string; command?: string } }
| { kind: "thinking"; payload: { text: string; truncated: boolean; chars: number } },
context: { sessionId: string | null; launchId: string | null }
) => void;
@@ -134,6 +137,16 @@ export interface ManagerRuntimeOpts {
* one-shot instruction like "Use `alook inbox pull` to read your messages."
*/
wakePromptFooter?: string;
+ /**
+ * When true, prepend a `[<local-tz ISO>]` timestamp to every prompt handed
+ * to the runtime driver (both spawn's initial prompt and mid-turn steer
+ * sends). Stamped inside `withFooter` — as close to "the moment the agent
+ * actually sees this text" as we can get — so the number reflects the real
+ * arrival wall-clock, not an earlier layer's timestamp. Off in tests so
+ * exact-string assertions on send/prompt stay stable; enabled in production
+ * via `createDaemon`.
+ */
+ stampWakePromptTime?: boolean;
/**
* Notified when a spawn fails BEFORE the runtime emits its handshake
* `runtime_event` (pre-establishment error). Typically wired to
@@ -180,6 +193,62 @@ export interface TimelineRecorder {
/** Max UTF-8 byte budget for `thinking` text in the audit log. */
const THINKING_MAX_BYTES = 4096;
+/**
+ * Max UTF-16 code units for a `Bash` tool_call's `command` summary. The wire
+ * schema caps `command` at 240 chars (see `AuditLogToolCallPayloadSchema`) and
+ * Zod's `.max()` measures UTF-16 length — so we truncate on the same unit an
+ * astral character (emoji) counts as 2. Truncating on codepoints would let an
+ * emoji-heavy command exceed 240 UTF-16 units and get rejected at the wire.
+ */
+const BASH_COMMAND_SUMMARY_MAX_CHARS = 200;
+
+/**
+ * Extract a short command summary from a tool_call's `input`. Bash-family
+ * tools carry a `command` string in most drivers (claude, cursor, kimi,
+ * opencode) — codex wraps it inside `input.item.command` or a `type:
+ * "commandExecution"` variant. Best-effort extraction: return the first
+ * non-empty line trimmed and truncated to `BASH_COMMAND_SUMMARY_MAX_CHARS`
+ * UTF-16 code units (ellipsis if cut, walking back one unit if the boundary
+ * would split a surrogate pair). Returns `undefined` if no plausible command
+ * string is present.
+ */
+export function extractBashCommandSummary(input: unknown): string | undefined {
+ const raw = pickCommandString(input);
+ if (typeof raw !== "string") return undefined;
+ const firstLine = raw.split("\n").map((s) => s.trim()).find((s) => s.length > 0);
+ if (!firstLine) return undefined;
+ if (firstLine.length <= BASH_COMMAND_SUMMARY_MAX_CHARS) return firstLine;
+ let end = BASH_COMMAND_SUMMARY_MAX_CHARS - 1;
+ const cu = firstLine.charCodeAt(end - 1);
+ if (cu >= 0xd800 && cu <= 0xdbff) end -= 1;
+ return firstLine.slice(0, end) + "…";
+}
+
+function pickCommandString(input: unknown): string | undefined {
+ if (!input || typeof input !== "object") return undefined;
+ const rec = input as Record<string, unknown>;
+ if (typeof rec.command === "string") return rec.command;
+ // codex `commandExecution` shape: input.item.command (array or string)
+ const item = rec.item as Record<string, unknown> | undefined;
+ if (item) {
+ if (typeof item.command === "string") return item.command;
+ if (Array.isArray(item.command)) return item.command.filter((v) => typeof v === "string").join(" ");
+ }
+ return undefined;
+}
+
+/**
+ * A `Bash` tool_call is the daemon proxy's shadow when — and only when — the
+ * command is `alook` or `alook <sub …>`. In that case the credential proxy
+ * emits an authoritative `cli_invocation` audit row and the tool_call would
+ * duplicate it. Any other Bash command (rm, sed, git, pnpm, echo, …) is user
+ * intent and must surface.
+ */
+export function isAlookShellCommand(command: string | undefined): boolean {
+ if (!command) return false;
+ return /^alook(\s|$)/.test(command.trimStart());
+}
+
/**
* Truncate a `thinking` string to at most `THINKING_MAX_BYTES` UTF-8 bytes
* without splitting a multi-byte sequence. Exported for tests. Callers get the
@@ -276,6 +345,7 @@ export class AgentProcessManager {
tickIntervalMs: 5_000,
staleThresholdMs: 120_000,
idleTimeoutMs: 300_000,
+ stampWakePromptTime: false,
...opts,
};
this.now = opts.now ?? (() => Date.now());
@@ -402,14 +472,35 @@ export class AgentProcessManager {
return this.opts.wakePromptFooter ? `${text}\n\n${this.opts.wakePromptFooter}` : text;
}
+ /**
+ * Prepend the local-tz wall-clock the moment BEFORE the text is handed to
+ * the runtime driver. Called at the very last mile — inside `doSpawn` right
+ * before `session.start(...)`, and inside `applyEffect`'s `send` branch
+ * right before `session.send(...)` — so the timestamp reflects "when the
+ * agent actually sees this text", not when the effect was scheduled. Gated
+ * by an opt-in flag so tests that assert on exact prompt strings stay
+ * stable; enabled in production via `createDaemon`.
+ */
+ private stampNow(text: string): string {
+ return this.opts.stampWakePromptTime ? `[${nowLocalISO()}] ${text}` : text;
+ }
+
private applyEffect(effect: ManagerEffect): void {
switch (effect.type) {
case "spawn":
+ // Timestamp is applied inside doSpawn just before session.start — the
+ // spawn path adds workdir resolution + system-prompt assembly + child
+ // wiring latency between here and there, which can be tens to hundreds
+ // of ms on cold start. Stamping now would lock in a moment that lags
+ // reality by the whole spawn setup window.
this.doSpawn(effect.agentId, this.withFooter(effect.prompt), effect.resumeSessionId);
break;
case "send": {
const session = this.sessions.get(effect.agentId);
- session?.send({ text: this.withFooter(effect.text), mode: effect.mode });
+ // Stamp at the moment the text hits `session.send`, not earlier —
+ // between effect creation and this call the event loop can drain other
+ // dispatches, and we want the timestamp to match the agent's arrival.
+ session?.send({ text: this.stampNow(this.withFooter(effect.text)), mode: effect.mode });
this.log.info("steering message sent to running agent", { agentId: effect.agentId, mode: effect.mode });
break;
}
@@ -579,7 +670,14 @@ export class AgentProcessManager {
this.dispatch({ type: "exit", agentId });
});
- void Promise.resolve(session.start({ text: prompt, sessionId: ctx.config.sessionId }))
+ // Stamp the wake-prompt timestamp AT the last mile — right before the
+ // driver's session sees the text — so the local-tz wall-clock the agent
+ // reads reflects the moment its process is being handed the prompt, not
+ // the moment the spawn effect was scheduled by the policy reducer. The
+ // difference matters on cold starts where system-prompt assembly + child
+ // wiring above adds tens/hundreds of ms.
+ const stampedPrompt = this.stampNow(prompt);
+ void Promise.resolve(session.start({ text: stampedPrompt, sessionId: ctx.config.sessionId }))
.then(() => {
// A concurrent stop()/terminate_stalled can race this in-flight
// start() and finish first — its `exit` handler above already
@@ -628,7 +726,7 @@ export class AgentProcessManager {
}
private onRuntimeEvent(agentId: string, e: unknown, runtimeId: string): void {
- const ev = e as { kind?: string; sessionId?: string; text?: string; name?: string };
+ const ev = e as { kind?: string; sessionId?: string; text?: string; name?: string; input?: unknown };
if (!ev?.kind) return;
// Bot audit hook — thinking + non-Bash tool_call, no correlation.
// Context carries the sessionId/launchId learned so far this launch so
@@ -649,14 +747,20 @@ export class AgentProcessManager {
// first so the audit log preserves thinking→action ordering.
this.flushThinkingAudit(agentId);
if (ev.kind === "tool_call" && typeof ev.name === "string") {
- // Bash suppression — the credential proxy emits the authoritative
- // `cli_invocation` when the agent invokes `alook` from a shell, and
- // raw non-`alook` Bash isn't user-visible in the audit spec.
- if (ev.name !== "Bash") {
+ // Bash-command suppression — a Bash call whose command is `alook`
+ // (or `alook <sub …>`) is already covered by the credential-proxy
+ // `cli_invocation` audit row; emitting a second `tool_call` here
+ // would double-count the same action. Every other Bash command
+ // (rm, sed, git, pnpm, echo …) is real user-visible work and must
+ // surface as a `tool_call` row with a short command summary.
+ const isBash = ev.name === "Bash";
+ const command = isBash ? extractBashCommandSummary(ev.input) : undefined;
+ const suppressed = isBash && isAlookShellCommand(command);
+ if (!suppressed) {
try {
this.opts.onBotAuditEvent(agentId, {
kind: "tool_call",
- payload: { name: ev.name },
+ payload: command ? { name: ev.name, command } : { name: ev.name },
}, {
sessionId: this.liveSessions.get(agentId) ?? null,
launchId: this.launchIds.get(agentId) ?? null,
diff --git a/src/daemon/src/timeline/timeline.test.ts b/src/daemon/src/timeline/timeline.test.ts
index 76d21cc33..95c52f500 100644
--- a/src/daemon/src/timeline/timeline.test.ts
+++ b/src/daemon/src/timeline/timeline.test.ts
@@ -124,7 +124,7 @@ describe("findResumableSession", () => {
});
describe("localISOString", () => {
- it("formats local time with a timezone offset", () => {
- expect(localISOString(NOW)).toMatch(/^2026-06-25T12:00:00[+-]\d{2}:\d{2}$/);
+ it("formats local time with milliseconds and a timezone offset", () => {
+ expect(localISOString(NOW)).toMatch(/^2026-06-25T12:00:00\.000[+-]\d{2}:\d{2}$/);
});
});
diff --git a/src/daemon/src/timeline/timeline.ts b/src/daemon/src/timeline/timeline.ts
index 06a5be68e..27c6f4d08 100644
--- a/src/daemon/src/timeline/timeline.ts
+++ b/src/daemon/src/timeline/timeline.ts
@@ -16,6 +16,9 @@ import { join } from "path";
import { acquireLock, releaseLock, lockPathFor } from "./filelock.js";
import type { ContextTimelineEntry } from "./types.js";
import type { Message } from "../server/contract.js";
+import { localISOString } from "../util/localTime.js";
+
+export { localISOString };
/* ------------------------------------------------------------------ */
/* Date / filename helpers (injectable clock) */
@@ -28,22 +31,6 @@ export function filenameForDate(date: Date): string {
return `${y}-${m}-${d}.jsonl`;
}
-/** Local-timezone ISO-8601 (with offset), e.g. 2026-06-25T17:11:05+08:00. */
-export function localISOString(now: Date): string {
- const tzOffset = -now.getTimezoneOffset();
- const sign = tzOffset >= 0 ? "+" : "-";
- const abs = Math.abs(tzOffset);
- const hh = String(Math.floor(abs / 60)).padStart(2, "0");
- const mm = String(abs % 60).padStart(2, "0");
- const y = now.getFullYear();
- const mo = String(now.getMonth() + 1).padStart(2, "0");
- const d = String(now.getDate()).padStart(2, "0");
- const h = String(now.getHours()).padStart(2, "0");
- const mi = String(now.getMinutes()).padStart(2, "0");
- const s = String(now.getSeconds()).padStart(2, "0");
- return `${y}-${mo}-${d}T${h}:${mi}:${s}${sign}${hh}:${mm}`;
-}
-
/** Filenames for the last `maxDays` days, today first. */
export function recentFilenames(maxDays: number, now: Date): string[] {
const out: string[] = [];
diff --git a/src/daemon/src/util/localTime.ts b/src/daemon/src/util/localTime.ts
new file mode 100644
index 000000000..11ac1dd92
--- /dev/null
+++ b/src/daemon/src/util/localTime.ts
@@ -0,0 +1,51 @@
+/**
+ * Local-timezone ISO-8601 helpers.
+ *
+ * The daemon presents time to the agent in its LOCAL timezone (with offset,
+ * e.g. `2026-06-25T17:11:05+08:00`) so `pulledAt`, wake-text timestamps, and
+ * per-message `.time` fields all agree with what the user sees on their
+ * machine. Server-side timestamps arrive as UTC (`...Z`); these helpers do the
+ * one-way conversion at the CLI/router boundary — nothing else in the daemon
+ * needs to know about timezones.
+ */
+
+/**
+ * Format a `Date` as local-tz ISO-8601 with milliseconds and offset, e.g.
+ * `2026-06-25T17:11:05.482+08:00`. Millisecond precision is deliberate — the
+ * agent sees `pulledAt`, wake-text timestamps, and `message.time` at this
+ * resolution, and second-only granularity would collapse sub-second stages
+ * (message-write / wake-dispatch / prompt-hand-off) into identical strings.
+ */
+export function localISOString(now: Date): string {
+ const tzOffset = -now.getTimezoneOffset();
+ const sign = tzOffset >= 0 ? "+" : "-";
+ const abs = Math.abs(tzOffset);
+ const hh = String(Math.floor(abs / 60)).padStart(2, "0");
+ const mm = String(abs % 60).padStart(2, "0");
+ const y = now.getFullYear();
+ const mo = String(now.getMonth() + 1).padStart(2, "0");
+ const d = String(now.getDate()).padStart(2, "0");
+ const h = String(now.getHours()).padStart(2, "0");
+ const mi = String(now.getMinutes()).padStart(2, "0");
+ const s = String(now.getSeconds()).padStart(2, "0");
+ const ms = String(now.getMilliseconds()).padStart(3, "0");
+ return `${y}-${mo}-${d}T${h}:${mi}:${s}.${ms}${sign}${hh}:${mm}`;
+}
+
+/** `new Date()` formatted in local-tz ISO-8601 with milliseconds and offset. */
+export function nowLocalISO(): string {
+ return localISOString(new Date());
+}
+
+/**
+ * Convert a UTC ISO-8601 string (server-stamped, ending in `Z`) into local-tz
+ * ISO-8601 with milliseconds and offset. Non-parseable input is returned
+ * unchanged — the CLI shouldn't drop a real message just because its `.time`
+ * didn't round-trip.
+ */
+export function toLocalISO(iso: string): string {
+ if (!iso) return iso;
+ const d = new Date(iso);
+ if (Number.isNaN(d.getTime())) return iso;
+ return localISOString(d);
+}
diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.ts
index eef586571..d89823659 100644
--- a/src/shared/src/schemas.ts
+++ b/src/shared/src/schemas.ts
@@ -1206,7 +1206,11 @@ export type CommunityAgentJoinServerRequest = z.infer<
// discriminated branches.
//
// - cli_invocation → the daemon's credential proxy handled an alook subcommand
-// - tool_call → the runtime invoked a non-Bash tool (Bash is suppressed)
+// - tool_call → the runtime invoked a tool. `Bash` calls whose command
+// starts with `alook ` are suppressed here (the proxy
+// emits the authoritative `cli_invocation` for those); any
+// other `Bash` command lands here with an optional
+// `command` summary attached.
// - thinking → excerpted thinking text, truncated at 4096 UTF-8 bytes
export const AuditLogCliInvocationPayloadSchema = z.object({
@@ -1214,6 +1218,8 @@ export const AuditLogCliInvocationPayloadSchema = z.object({
});
export const AuditLogToolCallPayloadSchema = z.object({
name: z.string().min(1),
+ /** First non-empty line of `input.command` for Bash-family tool_calls, truncated. */
+ command: z.string().max(240).optional(),
});
export const AuditLogThinkingPayloadSchema = z.object({
text: z.string(),
diff --git a/src/web/src/components/community/bots/bot-activity-modal.tsx b/src/web/src/components/community/bots/bot-activity-modal.tsx
index 3c850e30e..99bca2739 100644
--- a/src/web/src/components/community/bots/bot-activity-modal.tsx
+++ b/src/web/src/components/community/bots/bot-activity-modal.tsx
@@ -1,6 +1,6 @@
"use client"
-import { useEffect, useLayoutEffect, useMemo, useRef } from "react"
+import { useLayoutEffect, useMemo, useRef, useEffect } from "react"
import { AgentAvatar } from "@/components/avatar"
import {
Dialog,
@@ -22,12 +22,13 @@ import { BotActivityRow } from "./bot-activity-row"
* pushing a route.
*
* Reads like a developer log tail:
- * - oldest at the top, newest at the bottom;
+ * - oldest at the top, newest at the bottom (sorted by (createdAt, id));
* - auto-scrolls to the tail on open and on new live rows (only when the
* user was already near the tail — a reader scrolled up to inspect
* history is not yanked back);
- * - scroll UP to load the next (older) page; the scroll offset is
- * preserved across the prepend so the row under the eye stays fixed.
+ * - a "Load older" button at the top of the log fetches the next (older)
+ * page on click; the scroll offset is preserved across the prepend so
+ * the row under the eye stays fixed.
*
* Day dividers group rows chronologically without adding per-row chrome.
*/
@@ -53,9 +54,18 @@ export function BotActivityModal({
isFetchingNextPage,
} = useBotAuditLog(open ? bot?.id : null)
- // The API returns newest-first (createdAt DESC). The UI wants
- // oldest-first at the top so the log reads chronologically — flip once here.
- const chronological = useMemo(() => [...events].reverse(), [events])
+ // Merged stream = paginated GET (DESC) + live WS ring (arrival-ordered).
+ // The two are NOT a single monotonic sequence: a live event can carry a
+ // `createdAt` that interleaves with an older page, and a paginated older
+ // page prepends rows whose timestamps sit before the live tail. Sort
+ // once by `(createdAt, id)` ascending so the UI is chronological
+ // end-to-end — reversing alone would leave that jumbled.
+ const chronological = useMemo(() => {
+ return [...events].sort((a, b) => {
+ if (a.createdAt !== b.createdAt) return a.createdAt < b.createdAt ? -1 : 1
+ return a.id < b.id ? -1 : a.id > b.id ? 1 : 0
+ })
+ }, [events])
// Chronologically-adjacent rows are grouped under a shared day header,
// rendered when the day boundary changes. Cheap to compute at the render
@@ -63,23 +73,61 @@ export function BotActivityModal({
const grouped = useMemo(() => groupByDay(chronological), [chronological])
const scrollRef = useRef<HTMLDivElement | null>(null)
+ const bottomAnchorRef = useRef<HTMLDivElement | null>(null)
const lastCountRef = useRef(0)
const pendingOlderAnchorRef = useRef<number | null>(null)
+ const didInitialTailScrollRef = useRef(false)
- useEffect(() => {
+ const onLoadOlder = () => {
+ if (!hasNextPage || isFetchingNextPage) return
const el = scrollRef.current
- if (!el || !hasNextPage) return
- const onScroll = () => {
- if (isFetchingNextPage) return
- if (el.scrollTop < 80) {
- pendingOlderAnchorRef.current = el.scrollHeight
- void fetchNextPage()
- }
+ if (el) pendingOlderAnchorRef.current = el.scrollHeight
+ void fetchNextPage()
+ }
+
+ // Reset the once-per-open latch when the modal closes or the target bot
+ // changes, so the next open lands on the newest event again.
+ useEffect(() => {
+ if (!open) {
+ lastCountRef.current = 0
+ pendingOlderAnchorRef.current = null
+ didInitialTailScrollRef.current = false
}
- el.addEventListener("scroll", onScroll)
- return () => el.removeEventListener("scroll", onScroll)
- }, [fetchNextPage, hasNextPage, isFetchingNextPage])
+ }, [open, bot?.id])
+
+ // Snap to the newest event on first paint of an open cycle. The Radix
+ // Dialog mounts DialogContent inside a portal with an entrance animation,
+ // so relying on a `useLayoutEffect` that only fires when
+ // `chronological.length` changes can race the portal's first layout — the
+ // scroll fires before the container has its final height. Anchor + rAF
+ // guarantees the browser has laid out at least once before we jump.
+ useEffect(() => {
+ if (!open) return
+ if (didInitialTailScrollRef.current) return
+ if (chronological.length === 0) return
+ const anchor = bottomAnchorRef.current
+ const el = scrollRef.current
+ if (!anchor || !el) return
+ didInitialTailScrollRef.current = true
+ lastCountRef.current = chronological.length
+ // Two rAFs: one to let the portal layout settle, one to jump after the
+ // rows are actually painted. `scrollIntoView({ block: 'end' })` is
+ // instant (no smooth-scroll) so the reader doesn't see it move.
+ requestAnimationFrame(() => {
+ requestAnimationFrame(() => {
+ anchor.scrollIntoView({ block: "end" })
+ // Belt-and-braces: if the anchor was already in view before jumping,
+ // browsers sometimes no-op scrollIntoView — pin scrollTop explicitly.
+ el.scrollTop = el.scrollHeight
+ })
+ })
+ }, [open, chronological.length])
+ // After the initial tail scroll, handle two ongoing cases:
+ // 1. `pendingOlderAnchorRef` set — Load older prepended rows; preserve
+ // the reader's visible offset by shifting scrollTop by the height delta.
+ // 2. A new live event arrived and the reader was already near the tail —
+ // keep the tail pinned so streaming rows stay visible.
useLayoutEffect(() => {
const el = scrollRef.current
if (!el) return
@@ -89,26 +137,25 @@ export function BotActivityModal({
if (nextCount === 0) return
if (pendingOlderAnchorRef.current !== null) {
- const delta = el.scrollHeight - pendingOlderAnchorRef.current
- el.scrollTop = el.scrollTop + delta
+ // Only consume the anchor when rows were actually prepended. An older-page
+ // fetch that settles with zero new rows leaves the pending anchor stale;
+ // applying its `delta` on a later live-event render would yank the reader
+ // to a scrollTop derived from an unrelated prior scrollHeight.
+ if (nextCount > prevCount) {
+ const delta = el.scrollHeight - pendingOlderAnchorRef.current
+ el.scrollTop = el.scrollTop + delta
+ }
pendingOlderAnchorRef.current = null
return
}
+ if (!didInitialTailScrollRef.current) return
const nearTail = el.scrollHeight - (el.scrollTop + el.clientHeight) < 80
- const firstPaint = prevCount === 0
- if (firstPaint || (nextCount > prevCount && nearTail)) {
+ if (nextCount > prevCount && nearTail) {
el.scrollTop = el.scrollHeight
}
}, [chronological.length])
- useEffect(() => {
- if (!open) {
- lastCountRef.current = 0
- pendingOlderAnchorRef.current = null
- }
- }, [open, bot?.id])
-
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent
@@ -150,13 +197,16 @@ export function BotActivityModal({
<EmptyState />
) : (
<div className="pb-3">
- {isFetchingNextPage ? (
- <div className="py-2 text-center font-mono text-[10px] uppercase tracking-wider text-muted-foreground/60">
- Loading older
- </div>
- ) : hasNextPage ? (
- <div className="py-2 text-center font-mono text-[10px] uppercase tracking-wider text-muted-foreground/40">
- Scroll up for older
+ {hasNextPage ? (
+ <div className="flex justify-center py-2">
+ <button
+ type="button"
+ onClick={onLoadOlder}
+ disabled={isFetchingNextPage}
+ className="rounded-md px-3 py-1 font-mono text-[10px] uppercase tracking-wider text-muted-foreground/70 hover:bg-accent hover:text-foreground disabled:cursor-not-allowed disabled:opacity-60"
+ >
+ {isFetchingNextPage ? "Loading older" : "Load older"}
+ </button>
</div>
) : (
<div className="py-2 text-center font-mono text-[10px] uppercase tracking-wider text-muted-foreground/40">
@@ -171,6 +221,7 @@ export function BotActivityModal({
))}
</section>
))}
+ <div ref={bottomAnchorRef} aria-hidden />
</div>
)}
</div>
diff --git a/src/web/src/components/community/bots/bot-activity-row.tsx b/src/web/src/components/community/bots/bot-activity-row.tsx
index f8e9a74a7..d5d922e1b 100644
--- a/src/web/src/components/community/bots/bot-activity-row.tsx
+++ b/src/web/src/components/community/bots/bot-activity-row.tsx
@@ -77,8 +77,23 @@ function RowBody({
)
}
if (event.kind === "tool_call") {
- const p = event.payload as { name?: string } | null
- return <span className="font-mono text-[13px] text-foreground">{p?.name ?? "?"}</span>
+ const p = event.payload as { name?: string; command?: string } | null
+ const name = p?.name ?? "?"
+ // Bash-family calls carry a short command summary. Show it inline so the
+ // owner can distinguish `rm -rf tmp` from `git commit`; without it, all
+ // shell activity would collapse into an indistinguishable pile of "Bash".
+ if (p?.command) {
+ return (
+ <div
+ title={p.command}
+ className="truncate font-mono text-[13px] text-foreground"
+ >
+ {name} <span className="text-muted-foreground/60">·</span>{" "}
+ <span className="text-muted-foreground">{p.command}</span>
+ </div>
+ )
+ }
+ return <span className="font-mono text-[13px] text-foreground">{name}</span>
}
const p = event.payload as { text?: string; truncated?: boolean; chars?: number } | null
const text = p?.text ?? ""
diff --git a/src/web/src/hooks/community/use-bot-audit-log.ts b/src/web/src/hooks/community/use-bot-audit-log.ts
index fe0d47d85..ede5ff51a 100644
--- a/src/web/src/hooks/community/use-bot-audit-log.ts
+++ b/src/web/src/hooks/community/use-bot-audit-log.ts
@@ -94,9 +94,26 @@ export function useBotAuditLog(botId: string | null | undefined) {
)
}, [botId, enabled, liveEvents, qc, query.data])
+ // Flatten pages and dedup by id. The WS-prepend effect above dedups fresh
+ // live events against ALL cached pages before writing them into page 1,
+ // so on paper duplicates can't leak into the flattened array. In practice
+ // they can — a prepended live event on page 1 whose id later appears in a
+ // just-fetched older page 2 (the cursor race, when the daemon's
+ // server-stamped `createdAt` is close to the page-1 boundary), or a page
+ // re-fetch that overlaps at the seam. Dedup here so React never sees two
+ // rows with the same key. Keep first occurrence (page order = newest-first).
const events = useMemo(() => {
if (!query.data) return [] as AuditEvent[]
- return query.data.pages.flatMap((p) => p.events)
+ const seen = new Set<string>()
+ const out: AuditEvent[] = []
+ for (const p of query.data.pages) {
+ for (const e of p.events) {
+ if (seen.has(e.id)) continue
+ seen.add(e.id)
+ out.push(e)
+ }
+ }
+ return out
}, [query.data])
return {
diff --git a/src/web/src/lib/community/audit-log-payload.test.ts b/src/web/src/lib/community/audit-log-payload.test.ts
index 443f47388..68b9077fc 100644
--- a/src/web/src/lib/community/audit-log-payload.test.ts
+++ b/src/web/src/lib/community/audit-log-payload.test.ts
@@ -10,6 +10,19 @@ describe("parseAuditLogPayload", () => {
const p = parseAuditLogPayload("tool_call", JSON.stringify({ name: "Read" }))
expect(p).toEqual({ name: "Read" })
})
+ it("parses a Bash tool_call payload with a `command` summary", () => {
+ const p = parseAuditLogPayload(
+ "tool_call",
+ JSON.stringify({ name: "Bash", command: "rm -rf tmp" }),
+ )
+ expect(p).toEqual({ name: "Bash", command: "rm -rf tmp" })
+ })
+ it("rejects a tool_call `command` longer than 240 chars", () => {
+ const long = "x".repeat(241)
+ expect(parseAuditLogPayload("tool_call", JSON.stringify({ name: "Bash", command: long }))).toBe(
+ null,
+ )
+ })
it("parses a well-shaped thinking payload", () => {
const p = parseAuditLogPayload(
"thinking",