opencode-workflow-guard 1.19.1 → 1.19.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/docs/policies.md +12 -8
- package/docs/testing.md +3 -0
- package/package.json +6 -6
- package/src/lib/custom-tools.ts +28 -1
- package/src/lib/guard-api.ts +85 -0
- package/src/lib/permission-seat.ts +3 -1
- package/src/lib/tool-descriptions.ts +36 -0
- package/src/lib/types.ts +7 -1
- package/src/lib/v2-plugin.ts +236 -135
- package/src/policies/continuation.ts +107 -13
- package/src/workflow-guard.ts +17 -79
- package/test/test-e2e.mts +20 -4
- package/test/test.mts +396 -0
package/src/lib/v2-plugin.ts
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
* - `ctx.command.transform` for the server-side `/guard-status` command
|
|
11
11
|
* - `ctx.permission.hook("evaluate")` for the pre-execution deny seat
|
|
12
12
|
* - `ctx.shell.hook("create.before")` for env scrubbing
|
|
13
|
-
* - `ctx.mcp.list()` plus `mcp.
|
|
13
|
+
* - `ctx.mcp.list()` plus `mcp.status.changed` for the guarded-server inventory
|
|
14
14
|
* - `ctx.event.subscribe()` for tool outcomes, session lifecycle, and claims-vs-evidence
|
|
15
15
|
*
|
|
16
16
|
* The V1 SDK client surface (`TodoSdkClient`) is satisfied by an adapter so
|
|
@@ -22,7 +22,7 @@ import { Message } from "@opencode/ai/effect";
|
|
|
22
22
|
import { z } from "zod";
|
|
23
23
|
import { join, resolve } from "node:path";
|
|
24
24
|
import type { TodoSdkClient } from "./types.ts";
|
|
25
|
-
import { detectTodoCapability, recordTodoCapability, recordedTodoCapability, scanSessionTodos
|
|
25
|
+
import { detectTodoCapability, recordTodoCapability, recordedTodoCapability, scanSessionTodos } from "./v2-todo.ts";
|
|
26
26
|
import { findGitRoot, reloadProjectConfig } from "./project-config.ts";
|
|
27
27
|
import {
|
|
28
28
|
setWorkspaceRoot,
|
|
@@ -60,7 +60,7 @@ import { secretIn } from "../policies/secrets.ts";
|
|
|
60
60
|
import { createCustomTools, buildWorkflowGuardSystemGuidance } from "./custom-tools.ts";
|
|
61
61
|
import { isMutatingSurfaceTool, isReadOnlyRole, SHELL_TOOL_NAMES } from "./guard-dispatcher.ts";
|
|
62
62
|
import { ToolInvocationLifecycle } from "./tool-lifecycle.ts";
|
|
63
|
-
import { ToolOutcomeTracker
|
|
63
|
+
import { ToolOutcomeTracker } from "./tool-outcomes.ts";
|
|
64
64
|
import { EDIT_TOOL_NAMES, fetchParentSession, fetchParentSessionID, effectiveTodos } from "../policies/todo.ts";
|
|
65
65
|
import { currentGitBranch, isProtectedBranchName } from "../policies/git.ts";
|
|
66
66
|
import { checkCompletionClaims } from "../policies/completion.ts";
|
|
@@ -72,11 +72,21 @@ import { editTargets, runPostEditValidators, snapshotFile, type FileSnapshot } f
|
|
|
72
72
|
import { extractCommands, splitShellSegments } from "./shell.ts";
|
|
73
73
|
import { expandShellTargetPath, isPathOutsideWorkspace, OPENCODE_SCRATCH_DIR, redirectMutationsIn } from "../policies/boundary.ts";
|
|
74
74
|
import { audit, summarizeInput } from "./audit.ts";
|
|
75
|
-
import { asRecord,
|
|
75
|
+
import { asRecord, isSensitiveEnvKey } from "./utils.ts";
|
|
76
76
|
import { loadedPluginVersion } from "./version.ts";
|
|
77
|
-
import { clearContinuationState, continueUnfinishedSession, isGeneratedContinuationMessage, recordUserMessage } from "../policies/continuation.ts";
|
|
77
|
+
import { clearContinuationState, continueUnfinishedSession, isGeneratedContinuationMessage, markInterrupted, notifySessionRenamed, recordUserMessage } from "../policies/continuation.ts";
|
|
78
78
|
import { createRecoveryCheckpoint, finalizeRecoveryCheckpoint, nextRecoveryRun } from "./checkpoint.ts";
|
|
79
|
-
import { buildCompactionContext,
|
|
79
|
+
import { buildCompactionContext, guardToolCall } from "./guard-api.ts";
|
|
80
|
+
import { evaluateDogfoodGate } from "./dogfood.ts";
|
|
81
|
+
import {
|
|
82
|
+
appendToolDescriptionSuffix,
|
|
83
|
+
EDIT_MARKER,
|
|
84
|
+
EDIT_SUFFIX,
|
|
85
|
+
SUBAGENT_MARKER,
|
|
86
|
+
SUBAGENT_SUFFIX,
|
|
87
|
+
TODOWRITE_MARKER,
|
|
88
|
+
TODOWRITE_SUFFIX,
|
|
89
|
+
} from "./tool-descriptions.ts";
|
|
80
90
|
import { registerPluginInstance, releasePluginInstance } from "./plugin-instance.ts";
|
|
81
91
|
import { claimToolCall, releaseToolCallClaim } from "./call-claims.ts";
|
|
82
92
|
import { evaluatePermissionSeat } from "./permission-seat.ts";
|
|
@@ -94,11 +104,12 @@ type V2Context = Plugin.Context;
|
|
|
94
104
|
// capability) so builtin-only sessions are not gated forever. See v2-todo.ts.
|
|
95
105
|
|
|
96
106
|
function createV2SdkClient(ctx: V2Context): TodoSdkClient {
|
|
97
|
-
// V2 has no server-side log API or TUI surface
|
|
98
|
-
//
|
|
99
|
-
//
|
|
100
|
-
//
|
|
101
|
-
|
|
107
|
+
// V2 has no server-side log API or TUI surface. The client shim supplies
|
|
108
|
+
// only { app, session, lsp }, so there is no `tui.showToast` to call: block
|
|
109
|
+
// paths on V2 do not attempt a toast and rely on the thrown hook error,
|
|
110
|
+
// which is what actually reaches the model. Keep this adapter from logging
|
|
111
|
+
// anything beyond guard decision summaries.
|
|
112
|
+
const client: TodoSdkClient = {
|
|
102
113
|
app: {
|
|
103
114
|
log: async ({ body }) => {
|
|
104
115
|
try {
|
|
@@ -112,10 +123,32 @@ function createV2SdkClient(ctx: V2Context): TodoSdkClient {
|
|
|
112
123
|
const session = await ctx.session.get({ sessionID: path.id });
|
|
113
124
|
return { data: { parentID: (session as { parentID?: string }).parentID, title: (session as { title?: string }).title } };
|
|
114
125
|
},
|
|
126
|
+
// V2 only: forwards a synthetic message with `delivery`/`resume`.
|
|
127
|
+
// Its presence is also what marks this client as V2 for
|
|
128
|
+
// `policies/continuation.ts`, which is why the values travel here
|
|
129
|
+
// instead of through the shared `promptAsync` body type.
|
|
130
|
+
synthetic: async (opts) => {
|
|
131
|
+
await ctx.session.synthetic({
|
|
132
|
+
sessionID: opts.sessionID,
|
|
133
|
+
text: opts.text,
|
|
134
|
+
...(opts.delivery ? { delivery: opts.delivery } : {}),
|
|
135
|
+
...(opts.resume === undefined ? {} : { resume: opts.resume }),
|
|
136
|
+
});
|
|
137
|
+
},
|
|
115
138
|
promptAsync: async (opts) => {
|
|
116
|
-
|
|
139
|
+
const body = opts.body as {
|
|
140
|
+
parts: Array<{ type: "text"; text: string; synthetic?: boolean }>;
|
|
141
|
+
delivery?: "steer" | "queue";
|
|
142
|
+
resume?: boolean;
|
|
143
|
+
};
|
|
144
|
+
for (const part of body.parts) {
|
|
117
145
|
if (part.synthetic) {
|
|
118
|
-
await
|
|
146
|
+
await client.session!.synthetic!({
|
|
147
|
+
sessionID: opts.path.id,
|
|
148
|
+
text: part.text,
|
|
149
|
+
...(body.delivery ? { delivery: body.delivery } : {}),
|
|
150
|
+
...(body.resume === undefined ? {} : { resume: body.resume }),
|
|
151
|
+
});
|
|
119
152
|
} else {
|
|
120
153
|
await ctx.session.prompt({ sessionID: opts.path.id, text: part.text });
|
|
121
154
|
}
|
|
@@ -124,19 +157,9 @@ function createV2SdkClient(ctx: V2Context): TodoSdkClient {
|
|
|
124
157
|
},
|
|
125
158
|
lsp: {},
|
|
126
159
|
};
|
|
160
|
+
return client;
|
|
127
161
|
}
|
|
128
162
|
|
|
129
|
-
// ── Builtin tool description enrichment ───────────────────────────────────────
|
|
130
|
-
|
|
131
|
-
const TODOWRITE_SUFFIX =
|
|
132
|
-
"\n\nWorkflow Guard lifecycle: use todowrite to plan before working - it is the only view of progress the operator has, and every file mutation is gated on it. Each call replaces the complete task list: preserve every pending/in_progress task in subsequent updates until you explicitly mark it completed or cancelled, and do not omit active tasks when adding new work. A task may be marked completed only after its own work is recorded: the guard blocks a completion that has no file mutation in that task's active window, and one mutation cannot vouch for several completions. If a task is genuinely read-only (review, investigation, reading), append the marker `[read-only]` to its text; every such use is journaled. Use `cancelled` for work that was deliberately dropped. Marking every task completed triggers the finalization gate - fresh verification evidence (test run) is required after the last mutation, and protected-branch/conflict checks apply. Proactively call guard_next_tasks when planning work to discover existing roadmap/TODOs, and guard_status to check outstanding requirements.";
|
|
133
|
-
|
|
134
|
-
const EDIT_SUFFIX =
|
|
135
|
-
"\n\nWorkflow Guard requirement: Modifications require an active task in todowrite (status pending or in_progress), a feature branch (edits on main/master are blocked), and a prior read of existing files in the current session.";
|
|
136
|
-
|
|
137
|
-
const SUBAGENT_SUFFIX =
|
|
138
|
-
"\n\nWorkflow Guard subagent guidance: When spawning parallel worker subagents, use guard_worktree_create to isolate file mutations in separate worktrees. When conducting code reviews before task completion or PR creation, fetch the rubric with guard_review_rubric and provide it to a reviewer subagent to evaluate and record via record_review.";
|
|
139
|
-
|
|
140
163
|
// Builtin tool description enrichment. Candidates are matched against the
|
|
141
164
|
// host's tool registry; `ToolEditor.update` ignores missing IDs, so extra
|
|
142
165
|
// candidates are harmless no-ops.
|
|
@@ -155,9 +178,9 @@ const SUBAGENT_SUFFIX =
|
|
|
155
178
|
// - The V1 subagent tool `task` was renamed to `subagent`; both are kept as
|
|
156
179
|
// candidates for the same reason.
|
|
157
180
|
const ENRICHMENT_TARGETS: Array<{ candidates: string[]; suffix: string; marker: string }> = [
|
|
158
|
-
{ candidates: ["todowrite"], suffix: TODOWRITE_SUFFIX, marker:
|
|
159
|
-
{ candidates: [...EDIT_TOOL_NAMES], suffix: EDIT_SUFFIX, marker:
|
|
160
|
-
{ candidates: ["task", "subagent"], suffix: SUBAGENT_SUFFIX, marker:
|
|
181
|
+
{ candidates: ["todowrite"], suffix: TODOWRITE_SUFFIX, marker: TODOWRITE_MARKER },
|
|
182
|
+
{ candidates: [...EDIT_TOOL_NAMES], suffix: EDIT_SUFFIX, marker: EDIT_MARKER },
|
|
183
|
+
{ candidates: ["task", "subagent"], suffix: SUBAGENT_SUFFIX, marker: SUBAGENT_MARKER },
|
|
161
184
|
];
|
|
162
185
|
|
|
163
186
|
// ── Setup ─────────────────────────────────────────────────────────────────────
|
|
@@ -235,15 +258,20 @@ export const WorkflowGuardV2 = async (ctx: V2Context) => {
|
|
|
235
258
|
// definition.args is a V1 zod raw shape (plain object of zod fields);
|
|
236
259
|
// wrap it so the V2 registry receives a real StandardSchemaV1.
|
|
237
260
|
input: z.object(definition.args as unknown as z.ZodRawShape),
|
|
238
|
-
execute: async (rawInput: unknown, toolContext: { sessionID: string; id: string }) => {
|
|
261
|
+
execute: async (rawInput: unknown, toolContext: { sessionID: string; id: string; signal?: AbortSignal }) => {
|
|
239
262
|
// Only a session-bound workspace counts as the tool's own
|
|
240
263
|
// context; an unbound entry is a plugin-instance bootstrap
|
|
241
264
|
// and must not be presented to the tools as one.
|
|
242
265
|
const boundWorktree = getSessionBoundWorkspace(toolContext.sessionID);
|
|
266
|
+
// `signal` aborts when the session is interrupted. Guard tools
|
|
267
|
+
// pass it to cancellable work so an interrupt stops them
|
|
268
|
+
// instead of waiting out their own timeouts. V1's tool
|
|
269
|
+
// context supplies no signal, so the checks there are no-ops.
|
|
243
270
|
const result = await (definition.execute as (input: unknown, context: unknown) => Promise<unknown>)(rawInput, {
|
|
244
271
|
sessionID: toolContext.sessionID,
|
|
245
272
|
...(boundWorktree ? { worktree: boundWorktree } : {}),
|
|
246
273
|
directory: boundWorktree ?? effectiveRoot,
|
|
274
|
+
...(toolContext.signal ? { signal: toolContext.signal } : {}),
|
|
247
275
|
});
|
|
248
276
|
const text = typeof result === "string" ? result : (result as { output?: string } | undefined)?.output;
|
|
249
277
|
return {
|
|
@@ -256,8 +284,8 @@ export const WorkflowGuardV2 = async (ctx: V2Context) => {
|
|
|
256
284
|
for (const id of target.candidates) {
|
|
257
285
|
editor.update(id, (tool) => {
|
|
258
286
|
const description = typeof tool.description === "string" ? tool.description : "";
|
|
259
|
-
|
|
260
|
-
tool.description =
|
|
287
|
+
const next = appendToolDescriptionSuffix(description, target.suffix, target.marker);
|
|
288
|
+
if (next !== undefined) tool.description = next;
|
|
261
289
|
});
|
|
262
290
|
}
|
|
263
291
|
}
|
|
@@ -300,7 +328,6 @@ export const WorkflowGuardV2 = async (ctx: V2Context) => {
|
|
|
300
328
|
});
|
|
301
329
|
if (reason !== undefined) {
|
|
302
330
|
releaseToolCallClaim(instance.key, event.sessionID, event.id, event.tool);
|
|
303
|
-
await showBlockToast(reason);
|
|
304
331
|
const failureCount = event.sessionID ? toolOutcomes.getFailureCount(event.sessionID) : 0;
|
|
305
332
|
const circuitBreakerSuffix = failureCount >= 2
|
|
306
333
|
? "\n\n[Workflow Guard Circuit Breaker: Repeated failures detected in this session. Stop attempting alternative workarounds or shell laundering. Address the required step above directly, or inspect policy details with guard_status or guard_why.]"
|
|
@@ -316,7 +343,6 @@ export const WorkflowGuardV2 = async (ctx: V2Context) => {
|
|
|
316
343
|
const researchReason = liveDocsGatingReason(event.sessionID, event.tool, threshold, getResearchToolPatterns(toolWorktree));
|
|
317
344
|
if (researchReason !== undefined) {
|
|
318
345
|
releaseToolCallClaim(instance.key, event.sessionID, event.id, event.tool);
|
|
319
|
-
await showBlockToast(researchReason);
|
|
320
346
|
console.log(`[workflow-guard] warn: ${researchReason}`);
|
|
321
347
|
audit({
|
|
322
348
|
ts: new Date().toISOString(),
|
|
@@ -383,19 +409,13 @@ export const WorkflowGuardV2 = async (ctx: V2Context) => {
|
|
|
383
409
|
await ctx.tool.hook("execute.after", async (event) => {
|
|
384
410
|
releaseToolCallClaim(instance.key, event.sessionID, event.id, event.tool);
|
|
385
411
|
const startedAt = toolLifecycle.finish(event.sessionID, event.id);
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
decision: "allow",
|
|
394
|
-
phase: "outcome",
|
|
395
|
-
durationMs: outcome.durationMs,
|
|
396
|
-
reason: outcome.status,
|
|
397
|
-
});
|
|
398
|
-
}
|
|
412
|
+
recordV2ToolOutcome(toolOutcomes, effectiveRoot, {
|
|
413
|
+
tool: event.tool,
|
|
414
|
+
sessionID: event.sessionID,
|
|
415
|
+
callID: event.id,
|
|
416
|
+
status: event.status,
|
|
417
|
+
error: event.status === "error" ? event.error : undefined,
|
|
418
|
+
}, startedAt);
|
|
399
419
|
releaseFileClaims(event.sessionID, event.id);
|
|
400
420
|
if (event.tool === "read") {
|
|
401
421
|
const observation = toolLifecycle.takeReadObservation(event.sessionID, event.id);
|
|
@@ -695,10 +715,14 @@ export const WorkflowGuardV2 = async (ctx: V2Context) => {
|
|
|
695
715
|
} catch {}
|
|
696
716
|
|
|
697
717
|
// ── Event stream ──
|
|
718
|
+
// `types` is a host-side filter, so unrelated events never cross the stream
|
|
719
|
+
// or reach the handler. It must list every literal `handleV2Event` acts on:
|
|
720
|
+
// the test suite asserts this set matches the handler's comparisons, because
|
|
721
|
+
// a missing type silently disables its feature instead of failing loudly.
|
|
698
722
|
const controller = new AbortController();
|
|
699
723
|
void (async () => {
|
|
700
724
|
try {
|
|
701
|
-
for await (const raw of ctx.event.subscribe({ signal: controller.signal })) {
|
|
725
|
+
for await (const raw of ctx.event.subscribe({ types: V2_EVENT_TYPES, signal: controller.signal })) {
|
|
702
726
|
const event = raw as { type?: string; data?: unknown };
|
|
703
727
|
try {
|
|
704
728
|
await handleV2Event(event, {
|
|
@@ -721,93 +745,151 @@ export const WorkflowGuardV2 = async (ctx: V2Context) => {
|
|
|
721
745
|
};
|
|
722
746
|
};
|
|
723
747
|
|
|
748
|
+
// ── Tool outcome telemetry ────────────────────────────────────────────────────
|
|
749
|
+
|
|
750
|
+
/**
|
|
751
|
+
* Record one tool call's terminal outcome from `execute.after`.
|
|
752
|
+
*
|
|
753
|
+
* The former `session.message.content.updated` subscription never fired: that
|
|
754
|
+
* type is absent from `EventManifest.ServerDefinitions`, so no tool part was
|
|
755
|
+
* ever mapped and the repeated-failure circuit breaker plus the Policy 25
|
|
756
|
+
* research floor both read an always-zero count. `execute.after` does fire,
|
|
757
|
+
* including for a failed call, because the host triggers the hook with
|
|
758
|
+
* `status: "error"` before it rethrows. The error's own message feeds the
|
|
759
|
+
* tracker's signature, so repeat detection keys on what the model actually saw.
|
|
760
|
+
*/
|
|
761
|
+
function recordV2ToolOutcome(
|
|
762
|
+
toolOutcomes: ToolOutcomeTracker,
|
|
763
|
+
effectiveRoot: string,
|
|
764
|
+
event: {
|
|
765
|
+
tool: string;
|
|
766
|
+
sessionID?: string;
|
|
767
|
+
callID: string;
|
|
768
|
+
status?: "completed" | "error";
|
|
769
|
+
error?: { message?: string } | string;
|
|
770
|
+
},
|
|
771
|
+
startedAt?: number,
|
|
772
|
+
): void {
|
|
773
|
+
const status = event.status;
|
|
774
|
+
if (status !== "completed" && status !== "error") {
|
|
775
|
+
// The host's `execute.after` always carries a terminal status. A partial
|
|
776
|
+
// event from a harness or stub leaves it unknown, so record the
|
|
777
|
+
// optimistic completion that this hook used to record unconditionally
|
|
778
|
+
// rather than dropping the call from telemetry entirely. The audit row
|
|
779
|
+
// is kept here so this path does not lose the coverage it had before
|
|
780
|
+
// outcomes moved onto `execute.after`.
|
|
781
|
+
const fallback = toolOutcomes.recordFallbackCompleted(event.sessionID ?? "", event.callID, event.tool, startedAt === undefined ? undefined : Date.now() - startedAt);
|
|
782
|
+
if (fallback) {
|
|
783
|
+
audit({
|
|
784
|
+
ts: new Date().toISOString(),
|
|
785
|
+
sessionID: fallback.sessionID,
|
|
786
|
+
callID: fallback.callID,
|
|
787
|
+
tool: fallback.tool,
|
|
788
|
+
decision: "allow",
|
|
789
|
+
phase: "outcome",
|
|
790
|
+
durationMs: fallback.durationMs,
|
|
791
|
+
reason: fallback.status,
|
|
792
|
+
});
|
|
793
|
+
}
|
|
794
|
+
return;
|
|
795
|
+
}
|
|
796
|
+
const error = typeof event.error === "string" ? event.error : event.error?.message;
|
|
797
|
+
const outcome = toolOutcomes.record({
|
|
798
|
+
type: "tool",
|
|
799
|
+
sessionID: event.sessionID,
|
|
800
|
+
callID: event.callID,
|
|
801
|
+
tool: event.tool,
|
|
802
|
+
state: {
|
|
803
|
+
status,
|
|
804
|
+
error,
|
|
805
|
+
time: startedAt === undefined ? undefined : { start: startedAt, end: Date.now() },
|
|
806
|
+
},
|
|
807
|
+
});
|
|
808
|
+
if (!outcome) return;
|
|
809
|
+
// Policy 25 research floor (V1 parity): failures accrue debt; successful
|
|
810
|
+
// live-source lookups clear it. A failed research attempt never accrues
|
|
811
|
+
// debt, so a flaky lookup cannot deepen the block it was meant to escape.
|
|
812
|
+
if (isResearchTool(outcome.tool, getResearchToolPatterns(getSessionBoundWorkspace(outcome.sessionID) || effectiveRoot))) {
|
|
813
|
+
if (outcome.status !== "error") recordResearchLookup(outcome.sessionID);
|
|
814
|
+
} else if (outcome.status === "error") {
|
|
815
|
+
recordLiveDocsFailure(outcome.sessionID);
|
|
816
|
+
}
|
|
817
|
+
audit({
|
|
818
|
+
ts: new Date().toISOString(),
|
|
819
|
+
sessionID: outcome.sessionID,
|
|
820
|
+
callID: outcome.callID,
|
|
821
|
+
tool: outcome.tool,
|
|
822
|
+
decision: "allow",
|
|
823
|
+
phase: "outcome",
|
|
824
|
+
durationMs: outcome.durationMs,
|
|
825
|
+
reason: outcome.status,
|
|
826
|
+
});
|
|
827
|
+
if (outcome.status === "error" && outcome.repeatedFailureCount === 3) {
|
|
828
|
+
audit({
|
|
829
|
+
ts: new Date().toISOString(),
|
|
830
|
+
sessionID: outcome.sessionID,
|
|
831
|
+
callID: outcome.callID,
|
|
832
|
+
tool: outcome.tool,
|
|
833
|
+
decision: "allow",
|
|
834
|
+
phase: "event",
|
|
835
|
+
reason: "repeated-equivalent-failure:3",
|
|
836
|
+
});
|
|
837
|
+
console.log(`[workflow-guard] ${outcome.tool} failed equivalently 3 times in this session; change approach or inspect the underlying failure before retrying.`);
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
|
|
724
841
|
// ── Event handling ────────────────────────────────────────────────────────────
|
|
725
842
|
|
|
726
|
-
|
|
843
|
+
/**
|
|
844
|
+
* Every event type `handleV2Event` acts on.
|
|
845
|
+
*
|
|
846
|
+
* The subscription passes this as the host-side `types` filter. Each entry is a
|
|
847
|
+
* literal the handler compares against, so the two lists must stay identical: a
|
|
848
|
+
* type missing here is never delivered, and its feature becomes dead code that
|
|
849
|
+
* still type-checks. The suite asserts the match in both directions.
|
|
850
|
+
*
|
|
851
|
+
* Both idle triggers are listed because which one the host publishes is not
|
|
852
|
+
* settled, and `session.idle` is deprecated but still delivered.
|
|
853
|
+
*/
|
|
854
|
+
export const V2_EVENT_TYPES = [
|
|
855
|
+
"mcp.status.changed",
|
|
856
|
+
"session.text.ended",
|
|
857
|
+
"session.moved",
|
|
858
|
+
"session.renamed",
|
|
859
|
+
"session.execution.interrupted",
|
|
860
|
+
"session.status",
|
|
861
|
+
"session.idle",
|
|
862
|
+
"session.deleted",
|
|
863
|
+
"permission.asked",
|
|
864
|
+
"permission.replied",
|
|
865
|
+
] as const;
|
|
866
|
+
|
|
867
|
+
export interface V2EventState {
|
|
727
868
|
effectiveRoot: string;
|
|
728
869
|
client: unknown;
|
|
729
870
|
toolLifecycle: ToolInvocationLifecycle;
|
|
730
871
|
toolOutcomes: ToolOutcomeTracker;
|
|
731
|
-
/** Re-read the host MCP roster after `mcp.
|
|
872
|
+
/** Re-read the host MCP roster after `mcp.status.changed`. */
|
|
732
873
|
refreshMcpInventory?: () => Promise<void>;
|
|
733
874
|
}
|
|
734
875
|
|
|
735
|
-
async function handleV2Event(
|
|
876
|
+
export async function handleV2Event(
|
|
736
877
|
event: { type?: string; data?: unknown },
|
|
737
878
|
state: V2EventState,
|
|
738
879
|
): Promise<void> {
|
|
739
880
|
const { effectiveRoot, client, toolLifecycle, toolOutcomes } = state;
|
|
740
881
|
|
|
741
|
-
if (event.type === "mcp.
|
|
742
|
-
//
|
|
882
|
+
if (event.type === "mcp.status.changed") {
|
|
883
|
+
// A server's connection status settled (connected, failed, needs_auth,
|
|
884
|
+
// closed), which is when its tools become callable. Re-read the roster
|
|
743
885
|
// so a newly connected live-system server is guarded before its tools
|
|
744
|
-
//
|
|
886
|
+
// can be called. Widen-only: this can add tokens, never remove them.
|
|
887
|
+
// `mcp.resources.changed` is deliberately not a trigger: it reports
|
|
888
|
+
// resources, not tool availability.
|
|
745
889
|
await state.refreshMcpInventory?.();
|
|
746
890
|
return;
|
|
747
891
|
}
|
|
748
892
|
|
|
749
|
-
if (event.type === "session.message.content.updated") {
|
|
750
|
-
const data = event.data as { sessionID?: unknown; content?: unknown } | undefined;
|
|
751
|
-
const sessionID = typeof data?.sessionID === "string" ? data.sessionID : undefined;
|
|
752
|
-
if (!sessionID || !Array.isArray(data?.content)) return;
|
|
753
|
-
for (const part of data.content as Array<Record<string, unknown>>) {
|
|
754
|
-
if (part?.type !== "tool") continue;
|
|
755
|
-
const toolState = part.state as { status?: unknown; error?: { message?: string } | string } | undefined;
|
|
756
|
-
const status = toolState?.status;
|
|
757
|
-
if (status !== "completed" && status !== "error") continue;
|
|
758
|
-
// V2 keeps timing on the tool part itself (part.time), not inside state.
|
|
759
|
-
const partTime = part.time as { ran?: unknown; completed?: unknown } | undefined;
|
|
760
|
-
const start = typeof partTime?.ran === "number" ? partTime.ran : undefined;
|
|
761
|
-
const end = typeof partTime?.completed === "number" ? partTime.completed : undefined;
|
|
762
|
-
const mapped: ToolOutcomePart = {
|
|
763
|
-
type: "tool",
|
|
764
|
-
sessionID,
|
|
765
|
-
callID: part.id,
|
|
766
|
-
tool: toolPartName(part),
|
|
767
|
-
state: {
|
|
768
|
-
status,
|
|
769
|
-
error: typeof toolState?.error === "string" ? toolState.error : toolState?.error?.message,
|
|
770
|
-
time: { start, end },
|
|
771
|
-
},
|
|
772
|
-
};
|
|
773
|
-
const outcome = toolOutcomes.record(mapped);
|
|
774
|
-
if (outcome) {
|
|
775
|
-
// Policy 25 research floor (V1 parity): failures accrue debt;
|
|
776
|
-
// successful live-source lookups clear it. A failed research
|
|
777
|
-
// attempt never accrues debt, so a flaky lookup cannot deepen
|
|
778
|
-
// the block it was meant to escape.
|
|
779
|
-
if (isResearchTool(outcome.tool, getResearchToolPatterns(getSessionBoundWorkspace(outcome.sessionID) || effectiveRoot))) {
|
|
780
|
-
if (outcome.status !== "error") recordResearchLookup(outcome.sessionID);
|
|
781
|
-
} else if (outcome.status === "error") {
|
|
782
|
-
recordLiveDocsFailure(outcome.sessionID);
|
|
783
|
-
}
|
|
784
|
-
audit({
|
|
785
|
-
ts: new Date().toISOString(),
|
|
786
|
-
sessionID: outcome.sessionID,
|
|
787
|
-
callID: outcome.callID,
|
|
788
|
-
tool: outcome.tool,
|
|
789
|
-
decision: "allow",
|
|
790
|
-
phase: "outcome",
|
|
791
|
-
durationMs: outcome.durationMs,
|
|
792
|
-
reason: outcome.status,
|
|
793
|
-
});
|
|
794
|
-
if (outcome.status === "error" && outcome.repeatedFailureCount === 3) {
|
|
795
|
-
audit({
|
|
796
|
-
ts: new Date().toISOString(),
|
|
797
|
-
sessionID: outcome.sessionID,
|
|
798
|
-
callID: outcome.callID,
|
|
799
|
-
tool: outcome.tool,
|
|
800
|
-
decision: "allow",
|
|
801
|
-
phase: "event",
|
|
802
|
-
reason: "repeated-equivalent-failure:3",
|
|
803
|
-
});
|
|
804
|
-
console.log(`[workflow-guard] ${outcome.tool} failed equivalently 3 times in this session; change approach or inspect the underlying failure before retrying.`);
|
|
805
|
-
}
|
|
806
|
-
}
|
|
807
|
-
}
|
|
808
|
-
return;
|
|
809
|
-
}
|
|
810
|
-
|
|
811
893
|
if (event.type === "session.text.ended") {
|
|
812
894
|
const data = event.data as { sessionID?: unknown; text?: unknown } | undefined;
|
|
813
895
|
const sessionID = typeof data?.sessionID === "string" ? data.sessionID : undefined;
|
|
@@ -843,6 +925,14 @@ async function handleV2Event(
|
|
|
843
925
|
return;
|
|
844
926
|
}
|
|
845
927
|
|
|
928
|
+
if (event.type === "session.renamed") {
|
|
929
|
+
// The async title write landed. A pending continuation waits on this
|
|
930
|
+
// instead of polling for the full settle interval.
|
|
931
|
+
const data = event.data as { sessionID?: unknown } | undefined;
|
|
932
|
+
if (typeof data?.sessionID === "string") notifySessionRenamed(data.sessionID);
|
|
933
|
+
return;
|
|
934
|
+
}
|
|
935
|
+
|
|
846
936
|
if (event.type === "session.moved") {
|
|
847
937
|
// `session_move` relocates a session between checkouts, and the host
|
|
848
938
|
// announces it. On the pinned 2.2.0 SDK the V2 union carries
|
|
@@ -860,8 +950,36 @@ async function handleV2Event(
|
|
|
860
950
|
return;
|
|
861
951
|
}
|
|
862
952
|
|
|
863
|
-
if (event.type === "session.
|
|
864
|
-
|
|
953
|
+
if (event.type === "session.execution.interrupted") {
|
|
954
|
+
// `reason` is one of "user" | "shutdown" | "superseded" | "inactivity".
|
|
955
|
+
// Only "user" is user intent (Esc), so only it suspends automatic
|
|
956
|
+
// continuation. The other three are host-lifecycle events and must
|
|
957
|
+
// leave continuation state alone.
|
|
958
|
+
const data = event.data as { sessionID?: unknown; reason?: unknown } | undefined;
|
|
959
|
+
const sessionID = typeof data?.sessionID === "string" ? data.sessionID : undefined;
|
|
960
|
+
if (sessionID && data?.reason === "user") {
|
|
961
|
+
// Continuation state is keyed on the SDK client plus project root,
|
|
962
|
+
// so it must be reached inside the runtime state.
|
|
963
|
+
await runWithRuntimeState(effectiveRoot, client, () => markInterrupted(sessionID));
|
|
964
|
+
}
|
|
965
|
+
return;
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
// Idle is the trigger for automatic continuation. The host keeps two
|
|
969
|
+
// event types for it: `session.status` with `status.type === "idle"`, and
|
|
970
|
+
// the deprecated `session.idle`. Both are in
|
|
971
|
+
// `EventManifest.ServerDefinitions` on 2.0.15, 2.1.3, and 2.2.0, but which
|
|
972
|
+
// one the server actually publishes is not settled: the TUI derives idle
|
|
973
|
+
// from `session.execution.*` instead of consuming `session.status`, and an
|
|
974
|
+
// upstream report says `session.status` is declared but never published.
|
|
975
|
+
// Handling both keeps continuation working whichever one arrives, and adds
|
|
976
|
+
// no new trigger beyond what each host already emits. A host that emits
|
|
977
|
+
// both for one transition still sends a single prompt, because
|
|
978
|
+
// `continueUnfinishedSession` holds a per-session in-flight lock for the
|
|
979
|
+
// whole awaited send. The side effects keep their original order.
|
|
980
|
+
if (event.type === "session.status" || event.type === "session.idle") {
|
|
981
|
+
const data = event.data as { sessionID?: unknown; status?: { type?: unknown } } | undefined;
|
|
982
|
+
if (event.type === "session.status" && data?.status?.type !== "idle") return;
|
|
865
983
|
const sessionID = typeof data?.sessionID === "string" ? data.sessionID : undefined;
|
|
866
984
|
if (typeof sessionID === "string") {
|
|
867
985
|
releaseFileClaims(sessionID);
|
|
@@ -909,25 +1027,8 @@ async function handleV2Event(
|
|
|
909
1027
|
});
|
|
910
1028
|
return;
|
|
911
1029
|
}
|
|
912
|
-
// `command.executed` exists in the V2 event stream (`data: { name, sessionID,
|
|
913
|
-
// arguments, messageID }`) and carries what the V1 audit wanted: the slash
|
|
914
|
-
// command name, its arguments, and the session. It is journaled here rather
|
|
915
|
-
// than dropped, so a command that mutates workspace state stays attributable.
|
|
916
|
-
if (event.type === "command.executed") {
|
|
917
|
-
const data = event.data as { sessionID?: unknown; name?: unknown; arguments?: unknown } | undefined;
|
|
918
|
-
audit({
|
|
919
|
-
ts: new Date().toISOString(),
|
|
920
|
-
sessionID: typeof data?.sessionID === "string" ? data.sessionID : undefined,
|
|
921
|
-
tool: "command.executed",
|
|
922
|
-
decision: "allow",
|
|
923
|
-
phase: "event",
|
|
924
|
-
reason: typeof data?.name === "string" ? data.name : undefined,
|
|
925
|
-
input: summarizeInput({ name: data?.name, arguments: data?.arguments }),
|
|
926
|
-
});
|
|
927
|
-
return;
|
|
928
|
-
}
|
|
929
1030
|
// Note on V1 events without a V2 counterpart:
|
|
930
1031
|
// - `permission.updated`: replaced by `permission.asked`/`permission.replied` above.
|
|
931
|
-
// - `session.created`:
|
|
932
|
-
//
|
|
1032
|
+
// - `session.created`: V2 journals no create event; session state resets on
|
|
1033
|
+
// `session.deleted`.
|
|
933
1034
|
}
|