@vellumai/assistant 0.10.4-dev.202607020525.d9ced46 → 0.10.4-dev.202607020718.b100064
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/package.json +1 -1
- package/src/agent/loop.ts +31 -16
- package/src/daemon/conversation-agent-loop-handlers.ts +8 -0
- package/src/daemon/event-loop-watchdog.ts +22 -6
- package/src/permissions/checker.ts +2 -0
- package/src/permissions/ipc-risk-types.ts +1 -0
- package/src/persistence/__tests__/slow-sync-log.test.ts +91 -1
- package/src/persistence/slow-sync-log.ts +114 -16
- package/src/runtime/__tests__/agent-wake.test.ts +158 -1
- package/src/runtime/agent-wake.ts +28 -0
- package/src/util/platform.ts +11 -0
- package/src/workflows/library.test.ts +35 -20
- package/src/workflows/library.ts +105 -66
package/package.json
CHANGED
package/src/agent/loop.ts
CHANGED
|
@@ -15,6 +15,10 @@ import type { ToolActivityMetadata } from "../daemon/message-types/web-activity.
|
|
|
15
15
|
import { parseActualTokensFromError } from "../daemon/parse-actual-tokens-from-error.js";
|
|
16
16
|
import type { TrustContext } from "../daemon/trust-context.js";
|
|
17
17
|
import { stripHistoricalWebSearchResults } from "../daemon/web-search-history.js";
|
|
18
|
+
import {
|
|
19
|
+
timeSyncSection,
|
|
20
|
+
traceAsyncSection,
|
|
21
|
+
} from "../persistence/slow-sync-log.js";
|
|
18
22
|
import { HOOKS } from "../plugin-api/constants.js";
|
|
19
23
|
import type {
|
|
20
24
|
AgentLoopExitReason,
|
|
@@ -1507,15 +1511,20 @@ export class AgentLoop {
|
|
|
1507
1511
|
// the existing correction) so the calibrator learns the true
|
|
1508
1512
|
// bias against provider ground truth instead of ratcheting a
|
|
1509
1513
|
// feedback loop against its own corrected output.
|
|
1510
|
-
const
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1514
|
+
const preSendEstimatedTokens = timeSyncSection(
|
|
1515
|
+
"agent-loop:estimate-prompt-tokens",
|
|
1516
|
+
() => {
|
|
1517
|
+
const toolTokenBudget =
|
|
1518
|
+
currentTools.length > 0 ? estimateToolsTokens(currentTools) : 0;
|
|
1519
|
+
return estimatePromptTokensRaw(history, runSystemPrompt, {
|
|
1520
|
+
providerName: getCalibrationProviderKey(this.provider),
|
|
1521
|
+
toolTokenBudget,
|
|
1522
|
+
});
|
|
1518
1523
|
},
|
|
1524
|
+
(estimatedTokens) => ({
|
|
1525
|
+
estimatedTokens,
|
|
1526
|
+
messageCount: history.length,
|
|
1527
|
+
}),
|
|
1519
1528
|
);
|
|
1520
1529
|
lastPreSendEstimatedTokens = preSendEstimatedTokens;
|
|
1521
1530
|
rlog.info({ turn: toolUseTurns }, "LLM call start");
|
|
@@ -1523,7 +1532,11 @@ export class AgentLoop {
|
|
|
1523
1532
|
// Sanitize the outbound history right before sending: drop accumulated
|
|
1524
1533
|
// media, collapse old AX-tree snapshots, and convert historical
|
|
1525
1534
|
// web-search results to text. See {@link preModelCallSanitize}.
|
|
1526
|
-
const providerHistory =
|
|
1535
|
+
const providerHistory = timeSyncSection(
|
|
1536
|
+
"agent-loop:pre-model-call-sanitize",
|
|
1537
|
+
() => preModelCallSanitize(history),
|
|
1538
|
+
(sanitized) => ({ messageCount: sanitized.length }),
|
|
1539
|
+
);
|
|
1527
1540
|
|
|
1528
1541
|
// A `pre-model-call` hook (below) can defer this turn's assistant
|
|
1529
1542
|
// output; when set, the live text stream is held so an
|
|
@@ -1634,9 +1647,9 @@ export class AgentLoop {
|
|
|
1634
1647
|
deferAssistantOutput: false,
|
|
1635
1648
|
logger: rlog,
|
|
1636
1649
|
};
|
|
1637
|
-
const finalPreModelCtx = await
|
|
1638
|
-
|
|
1639
|
-
preModelCtx,
|
|
1650
|
+
const finalPreModelCtx = await traceAsyncSection(
|
|
1651
|
+
"agent-loop:pre-model-call-hook",
|
|
1652
|
+
() => runHook(HOOKS.PRE_MODEL_CALL, preModelCtx),
|
|
1640
1653
|
);
|
|
1641
1654
|
// Emit a changed event when the hook mutated the prompt. Compare
|
|
1642
1655
|
// against the pre-hook value from providerOptions, not
|
|
@@ -1705,9 +1718,8 @@ export class AgentLoop {
|
|
|
1705
1718
|
latencyTracker?.mark("request_sent");
|
|
1706
1719
|
let response: ProviderResponse;
|
|
1707
1720
|
try {
|
|
1708
|
-
response = await
|
|
1709
|
-
providerHistory,
|
|
1710
|
-
providerOptions,
|
|
1721
|
+
response = await traceAsyncSection("agent-loop:provider-send", () =>
|
|
1722
|
+
this.provider.sendMessage(providerHistory, providerOptions),
|
|
1711
1723
|
);
|
|
1712
1724
|
} catch (llmCallError) {
|
|
1713
1725
|
// Skip recording on abort — the user cancelled the request and
|
|
@@ -1803,7 +1815,10 @@ export class AgentLoop {
|
|
|
1803
1815
|
decision: "stop",
|
|
1804
1816
|
logger: rlog,
|
|
1805
1817
|
};
|
|
1806
|
-
const result = await
|
|
1818
|
+
const result = await traceAsyncSection(
|
|
1819
|
+
"agent-loop:post-model-call-hook",
|
|
1820
|
+
() => runHook(HOOKS.POST_MODEL_CALL, ctx),
|
|
1821
|
+
);
|
|
1807
1822
|
return {
|
|
1808
1823
|
finalized: { role: "assistant", content: result.content },
|
|
1809
1824
|
decision: result.decision,
|
|
@@ -48,6 +48,7 @@ import {
|
|
|
48
48
|
recordRequestLog,
|
|
49
49
|
setAgentLoopExitReasonOnLatestLog,
|
|
50
50
|
} from "../persistence/llm-request-log-store.js";
|
|
51
|
+
import { endSection, markSection } from "../persistence/slow-sync-log.js";
|
|
51
52
|
import type { ContextWindowResult } from "../plugins/defaults/compaction/window-manager.js";
|
|
52
53
|
import { indexMessageNow } from "../plugins/defaults/memory/indexer.js";
|
|
53
54
|
import { backfillMemoryRecallLogMessageId } from "../plugins/defaults/memory/memory-recall-log-store.js";
|
|
@@ -2399,6 +2400,11 @@ export async function dispatchAgentEvent(
|
|
|
2399
2400
|
deps: EventHandlerDeps,
|
|
2400
2401
|
event: AgentEvent,
|
|
2401
2402
|
): Promise<void> {
|
|
2403
|
+
// Section-trail breadcrumb for event-loop freeze attribution: the dispatch
|
|
2404
|
+
// is the single choke point for per-turn persistence work (message writes,
|
|
2405
|
+
// usage/request-log rows, SSE fan-out), so a watchdog report during a
|
|
2406
|
+
// handler names the event type that was being processed.
|
|
2407
|
+
const sectionMark = markSection(`agent-event:${event.type}`);
|
|
2402
2408
|
try {
|
|
2403
2409
|
switch (event.type) {
|
|
2404
2410
|
case "llm_call_started":
|
|
@@ -2706,5 +2712,7 @@ export async function dispatchAgentEvent(
|
|
|
2706
2712
|
) {
|
|
2707
2713
|
throw err;
|
|
2708
2714
|
}
|
|
2715
|
+
} finally {
|
|
2716
|
+
endSection(sectionMark);
|
|
2709
2717
|
}
|
|
2710
2718
|
}
|
|
@@ -20,11 +20,12 @@
|
|
|
20
20
|
* What it does NOT do: capture the JS stack of the blocking operation. JS is
|
|
21
21
|
* single-threaded, so while the loop is blocked no callback — including this one
|
|
22
22
|
* — can run; by the time the tick fires, the offending synchronous call has
|
|
23
|
-
* returned and its stack is gone.
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
23
|
+
* returned and its stack is gone. Instead, each freeze report carries the
|
|
24
|
+
* section trail (`persistence/slow-sync-log.ts`): the recent instrumented
|
|
25
|
+
* sections with their start/end ages relative to the report. The newest entry
|
|
26
|
+
* older than `blockedMs` that hadn't ended when the block began names — or
|
|
27
|
+
* brackets — the code that froze. For sub-threshold contributors, time the
|
|
28
|
+
* subsystem's synchronous calls at their source with `timeSyncSection`.
|
|
28
29
|
*
|
|
29
30
|
* A cumulative event-loop-delay histogram is separately exposed pull-based over
|
|
30
31
|
* SSE diagnostics (`runtime/routes/events-routes.ts`); this watchdog is the
|
|
@@ -33,6 +34,10 @@
|
|
|
33
34
|
|
|
34
35
|
import * as Sentry from "@sentry/node";
|
|
35
36
|
|
|
37
|
+
import {
|
|
38
|
+
getSectionTrail,
|
|
39
|
+
type SectionTrailEntry,
|
|
40
|
+
} from "../persistence/slow-sync-log.js";
|
|
36
41
|
import { recordWatchdogEvent } from "../telemetry/watchdog-events-store.js";
|
|
37
42
|
import { getLogger } from "../util/logger.js";
|
|
38
43
|
|
|
@@ -84,8 +89,17 @@ export function evaluateTick(
|
|
|
84
89
|
export const EVENT_LOOP_BLOCKED_CHECK_NAME = "event_loop_blocked";
|
|
85
90
|
|
|
86
91
|
function reportBlock(blockedMs: number, thresholdMs: number): void {
|
|
92
|
+
// Attribution breadcrumbs: the block began ~`blockedMs` before this report,
|
|
93
|
+
// so the newest trail entry started at least that long ago — and not yet
|
|
94
|
+
// ended by then — is the section that was running when the loop froze.
|
|
95
|
+
let sectionTrail: SectionTrailEntry[] = [];
|
|
96
|
+
try {
|
|
97
|
+
sectionTrail = getSectionTrail();
|
|
98
|
+
} catch {
|
|
99
|
+
// Diagnostics-only — never let it escape the timer callback.
|
|
100
|
+
}
|
|
87
101
|
log.warn(
|
|
88
|
-
{ blockedMs, thresholdMs, tickIntervalMs: TICK_INTERVAL_MS },
|
|
102
|
+
{ blockedMs, thresholdMs, tickIntervalMs: TICK_INTERVAL_MS, sectionTrail },
|
|
89
103
|
"event loop blocked",
|
|
90
104
|
);
|
|
91
105
|
// Persist a `watchdog` telemetry event so the platform can surface
|
|
@@ -101,6 +115,7 @@ function reportBlock(blockedMs: number, thresholdMs: number): void {
|
|
|
101
115
|
detail: {
|
|
102
116
|
threshold_ms: thresholdMs,
|
|
103
117
|
tick_interval_ms: TICK_INTERVAL_MS,
|
|
118
|
+
section_trail: sectionTrail,
|
|
104
119
|
},
|
|
105
120
|
});
|
|
106
121
|
} catch {
|
|
@@ -114,6 +129,7 @@ function reportBlock(blockedMs: number, thresholdMs: number): void {
|
|
|
114
129
|
blocked_ms: blockedMs,
|
|
115
130
|
threshold_ms: thresholdMs,
|
|
116
131
|
tick_interval_ms: TICK_INTERVAL_MS,
|
|
132
|
+
section_trail: sectionTrail,
|
|
117
133
|
});
|
|
118
134
|
Sentry.captureMessage(EVENT_LOOP_BLOCKED_CHECK_NAME);
|
|
119
135
|
});
|
|
@@ -27,6 +27,7 @@ import {
|
|
|
27
27
|
getWorkspacePluginsDir,
|
|
28
28
|
getWorkspaceRoutesDir,
|
|
29
29
|
getWorkspaceToolsDir,
|
|
30
|
+
getWorkspaceWorkflowsDir,
|
|
30
31
|
} from "../util/platform.js";
|
|
31
32
|
import {
|
|
32
33
|
type ApprovalContext,
|
|
@@ -311,6 +312,7 @@ function buildFileContext(): FileContext {
|
|
|
311
312
|
pluginsDir: resolveRealPath(getWorkspacePluginsDir()),
|
|
312
313
|
toolsDir: resolveRealPath(getWorkspaceToolsDir()),
|
|
313
314
|
routesDir: resolveRealPath(getWorkspaceRoutesDir()),
|
|
315
|
+
workflowsDir: resolveRealPath(getWorkspaceWorkflowsDir()),
|
|
314
316
|
actorTokenSigningKeyPath: join(protectedDir, "actor-token-signing-key"),
|
|
315
317
|
skillSourceDirs: getSkillRoots(config.skills.load.extraDirs).map(
|
|
316
318
|
resolveRealPath,
|
|
@@ -1,10 +1,15 @@
|
|
|
1
|
-
import { describe, expect, test } from "bun:test";
|
|
1
|
+
import { beforeEach, describe, expect, test } from "bun:test";
|
|
2
2
|
|
|
3
3
|
import {
|
|
4
|
+
endSection,
|
|
5
|
+
getSectionTrail,
|
|
6
|
+
markSection,
|
|
4
7
|
reportSlowSync,
|
|
8
|
+
resetSectionTrailForTests,
|
|
5
9
|
SLOW_SYNC_CHECK_NAME,
|
|
6
10
|
SLOW_SYNC_THRESHOLD_MS,
|
|
7
11
|
timeSyncSection,
|
|
12
|
+
traceAsyncSection,
|
|
8
13
|
} from "../slow-sync-log.js";
|
|
9
14
|
|
|
10
15
|
describe("slow-sync-log", () => {
|
|
@@ -63,3 +68,88 @@ describe("slow-sync-log", () => {
|
|
|
63
68
|
).not.toThrow();
|
|
64
69
|
});
|
|
65
70
|
});
|
|
71
|
+
|
|
72
|
+
describe("section trail", () => {
|
|
73
|
+
beforeEach(() => {
|
|
74
|
+
resetSectionTrailForTests();
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
test("marks appear newest-first with ago values relative to now", () => {
|
|
78
|
+
const first = markSection("test:first");
|
|
79
|
+
endSection(first);
|
|
80
|
+
markSection("test:second");
|
|
81
|
+
|
|
82
|
+
const trail = getSectionTrail(performance.now() + 100);
|
|
83
|
+
expect(trail.map((e) => e.label)).toEqual(["test:second", "test:first"]);
|
|
84
|
+
// Both marks started before the reference "now".
|
|
85
|
+
for (const entry of trail) {
|
|
86
|
+
expect(entry.startedAgoMs).toBeGreaterThanOrEqual(100);
|
|
87
|
+
}
|
|
88
|
+
// Only the ended mark carries an end age.
|
|
89
|
+
expect(trail[0]?.endedAgoMs).toBeUndefined();
|
|
90
|
+
expect(trail[1]?.endedAgoMs).toBeGreaterThanOrEqual(100);
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
test("endSection returns the section's elapsed time", () => {
|
|
94
|
+
const mark = markSection("test:elapsed");
|
|
95
|
+
const elapsed = endSection(mark);
|
|
96
|
+
expect(elapsed).toBeGreaterThanOrEqual(0);
|
|
97
|
+
expect(mark.endedAt).toBeDefined();
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
test("trail is capacity-bounded, evicting oldest marks", () => {
|
|
101
|
+
for (let i = 0; i < 20; i++) {
|
|
102
|
+
endSection(markSection(`test:mark-${i}`));
|
|
103
|
+
}
|
|
104
|
+
const trail = getSectionTrail();
|
|
105
|
+
expect(trail.length).toBe(16);
|
|
106
|
+
// Newest-first: the most recent mark leads, the earliest four are evicted.
|
|
107
|
+
expect(trail[0]?.label).toBe("test:mark-19");
|
|
108
|
+
expect(trail[trail.length - 1]?.label).toBe("test:mark-4");
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
test("timeSyncSection leaves an ended mark in the trail", () => {
|
|
112
|
+
timeSyncSection("test:timed", () => 1);
|
|
113
|
+
const trail = getSectionTrail();
|
|
114
|
+
expect(trail[0]?.label).toBe("test:timed");
|
|
115
|
+
expect(trail[0]?.endedAgoMs).toBeDefined();
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
test("timeSyncSection ends its mark when the section throws", () => {
|
|
119
|
+
expect(() =>
|
|
120
|
+
timeSyncSection("test:timed-throw", () => {
|
|
121
|
+
throw new Error("boom");
|
|
122
|
+
}),
|
|
123
|
+
).toThrow("boom");
|
|
124
|
+
const trail = getSectionTrail();
|
|
125
|
+
expect(trail[0]?.label).toBe("test:timed-throw");
|
|
126
|
+
expect(trail[0]?.endedAgoMs).toBeDefined();
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
test("traceAsyncSection returns the value and ends the mark across an await", async () => {
|
|
130
|
+
const result = await traceAsyncSection("test:async", async () => {
|
|
131
|
+
// While awaited, the mark is open.
|
|
132
|
+
expect(getSectionTrail()[0]?.label).toBe("test:async");
|
|
133
|
+
expect(getSectionTrail()[0]?.endedAgoMs).toBeUndefined();
|
|
134
|
+
await Promise.resolve();
|
|
135
|
+
return "ok";
|
|
136
|
+
});
|
|
137
|
+
expect(result).toBe("ok");
|
|
138
|
+
const trail = getSectionTrail();
|
|
139
|
+
expect(trail[0]?.label).toBe("test:async");
|
|
140
|
+
expect(trail[0]?.endedAgoMs).toBeDefined();
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
test("traceAsyncSection ends the mark when the span rejects", async () => {
|
|
144
|
+
let thrown: unknown;
|
|
145
|
+
try {
|
|
146
|
+
await traceAsyncSection("test:async-throw", async () => {
|
|
147
|
+
throw new Error("boom");
|
|
148
|
+
});
|
|
149
|
+
} catch (err) {
|
|
150
|
+
thrown = err;
|
|
151
|
+
}
|
|
152
|
+
expect(thrown).toBeInstanceOf(Error);
|
|
153
|
+
expect(getSectionTrail()[0]?.endedAgoMs).toBeDefined();
|
|
154
|
+
});
|
|
155
|
+
});
|
|
@@ -9,16 +9,24 @@
|
|
|
9
9
|
* being single-threaded itself, cannot capture *what* was running: by the
|
|
10
10
|
* time its tick fires the blocking call has returned and its stack is gone.
|
|
11
11
|
*
|
|
12
|
-
* This module fills that gap
|
|
13
|
-
* {@link timeSyncSection} (or call {@link reportSlowSync} with a measured
|
|
14
|
-
* duration); when it blocks past {@link SLOW_SYNC_THRESHOLD_MS} it logs a
|
|
15
|
-
* structured warning naming the call site and records a `watchdog`
|
|
16
|
-
* telemetry event, so the next freeze is attributable to a specific
|
|
17
|
-
* operation instead of an anonymous gap in the logs.
|
|
12
|
+
* This module fills that gap two ways:
|
|
18
13
|
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
14
|
+
* 1. **Threshold reports** — wrap a known-heavy synchronous section with
|
|
15
|
+
* {@link timeSyncSection} (or call {@link reportSlowSync} with a measured
|
|
16
|
+
* duration); when it blocks past {@link SLOW_SYNC_THRESHOLD_MS} it logs a
|
|
17
|
+
* structured warning naming the call site and records a `watchdog`
|
|
18
|
+
* telemetry event. The threshold is deliberately below the watchdog's own
|
|
19
|
+
* 5s floor so sub-watchdog contributors are still named. Override with
|
|
20
|
+
* `VELLUM_SLOW_SYNC_THRESHOLD_MS`.
|
|
21
|
+
*
|
|
22
|
+
* 2. **Section trail** — a small in-memory ring of the most recently entered
|
|
23
|
+
* instrumented sections ({@link markSection} / {@link traceAsyncSection};
|
|
24
|
+
* {@link timeSyncSection} marks automatically). The event-loop watchdog
|
|
25
|
+
* attaches {@link getSectionTrail} to every freeze report: because the
|
|
26
|
+
* loop is single-threaded, the newest mark still un-ended at block start
|
|
27
|
+
* (entries older than `blockedMs`) names — or tightly brackets — the code
|
|
28
|
+
* that froze, even when the block sits in a section nobody thought to
|
|
29
|
+
* time. Marks record only static labels, never content.
|
|
22
30
|
*/
|
|
23
31
|
|
|
24
32
|
import { getLogger } from "../util/logger.js";
|
|
@@ -42,6 +50,95 @@ export const SLOW_SYNC_THRESHOLD_MS = ((): number => {
|
|
|
42
50
|
*/
|
|
43
51
|
export const SLOW_SYNC_CHECK_NAME = "slow_sync_operation";
|
|
44
52
|
|
|
53
|
+
/** One recorded section entry: a static label plus monotonic start/end stamps. */
|
|
54
|
+
export interface SectionMark {
|
|
55
|
+
label: string;
|
|
56
|
+
startedAt: number;
|
|
57
|
+
endedAt?: number;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* How many section marks the trail retains. Sized so the sections between a
|
|
62
|
+
* container mark (e.g. an agent-event dispatch) and a freeze — typically a
|
|
63
|
+
* handful of nested query marks — don't evict the container before the
|
|
64
|
+
* watchdog reads the trail.
|
|
65
|
+
*/
|
|
66
|
+
const SECTION_TRAIL_CAPACITY = 16;
|
|
67
|
+
|
|
68
|
+
const sectionTrail: SectionMark[] = [];
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Record that an instrumented section is starting. Returns the mark so the
|
|
72
|
+
* caller can stamp its completion with {@link endSection}. Cheap enough for
|
|
73
|
+
* hot paths: one small allocation and a bounded-array push.
|
|
74
|
+
*/
|
|
75
|
+
export function markSection(label: string): SectionMark {
|
|
76
|
+
const mark: SectionMark = { label, startedAt: performance.now() };
|
|
77
|
+
sectionTrail.push(mark);
|
|
78
|
+
if (sectionTrail.length > SECTION_TRAIL_CAPACITY) {
|
|
79
|
+
sectionTrail.shift();
|
|
80
|
+
}
|
|
81
|
+
return mark;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Stamp a mark's completion; returns the section's elapsed milliseconds. */
|
|
85
|
+
export function endSection(mark: SectionMark): number {
|
|
86
|
+
mark.endedAt = performance.now();
|
|
87
|
+
return mark.endedAt - mark.startedAt;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Trail a section that spans an `await` (a hook chain, a provider call). The
|
|
92
|
+
* mark stays open for the span's full wall time — sections entered by work
|
|
93
|
+
* interleaving on the loop during the await appear as newer trail entries, so
|
|
94
|
+
* a freeze inside the span is still bracketed correctly. Wall time is NOT
|
|
95
|
+
* reported as a slow sync: an awaited span legitimately spends most of it
|
|
96
|
+
* off-loop.
|
|
97
|
+
*/
|
|
98
|
+
export async function traceAsyncSection<T>(
|
|
99
|
+
label: string,
|
|
100
|
+
fn: () => Promise<T>,
|
|
101
|
+
): Promise<T> {
|
|
102
|
+
const mark = markSection(label);
|
|
103
|
+
try {
|
|
104
|
+
return await fn();
|
|
105
|
+
} finally {
|
|
106
|
+
endSection(mark);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** A trail entry made relative to "now" for freeze reports. */
|
|
111
|
+
export interface SectionTrailEntry {
|
|
112
|
+
label: string;
|
|
113
|
+
startedAgoMs: number;
|
|
114
|
+
/** Absent while the section is still running (or never ended). */
|
|
115
|
+
endedAgoMs?: number;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Newest-first snapshot of recent section marks, ages relative to `now`.
|
|
120
|
+
* Reading it against a freeze report: the block began ~`blockedMs` ago, so
|
|
121
|
+
* the newest entry with `startedAgoMs >= blockedMs` that has no `endedAgoMs`
|
|
122
|
+
* (or ended after the block began) is the section that was running when the
|
|
123
|
+
* loop froze.
|
|
124
|
+
*/
|
|
125
|
+
export function getSectionTrail(
|
|
126
|
+
now: number = performance.now(),
|
|
127
|
+
): SectionTrailEntry[] {
|
|
128
|
+
return [...sectionTrail].reverse().map((mark) => ({
|
|
129
|
+
label: mark.label,
|
|
130
|
+
startedAgoMs: Math.round(now - mark.startedAt),
|
|
131
|
+
...(mark.endedAt !== undefined
|
|
132
|
+
? { endedAgoMs: Math.round(now - mark.endedAt) }
|
|
133
|
+
: {}),
|
|
134
|
+
}));
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Test isolation only — the trail is process-global module state. */
|
|
138
|
+
export function resetSectionTrailForTests(): void {
|
|
139
|
+
sectionTrail.length = 0;
|
|
140
|
+
}
|
|
141
|
+
|
|
45
142
|
/**
|
|
46
143
|
* Report a synchronous section that blocked the event loop for `elapsedMs`.
|
|
47
144
|
* No-op below {@link SLOW_SYNC_THRESHOLD_MS}. `label` names the call site
|
|
@@ -79,20 +176,21 @@ export function reportSlowSync(
|
|
|
79
176
|
|
|
80
177
|
/**
|
|
81
178
|
* Time a synchronous section, returning its value, and {@link reportSlowSync}
|
|
82
|
-
* it when it blocks past the threshold.
|
|
83
|
-
*
|
|
84
|
-
*
|
|
85
|
-
*
|
|
179
|
+
* it when it blocks past the threshold. Every section also lands in the
|
|
180
|
+
* section trail, so watchdog freeze reports can place it on the timeline.
|
|
181
|
+
* `detail` is evaluated only on success, from the section's result, so it can
|
|
182
|
+
* report a computed count. A thrown error is still reported (the failed op
|
|
183
|
+
* still blocked) and then rethrown unchanged.
|
|
86
184
|
*/
|
|
87
185
|
export function timeSyncSection<T>(
|
|
88
186
|
label: string,
|
|
89
187
|
fn: () => T,
|
|
90
188
|
detail?: (result: T) => Record<string, unknown>,
|
|
91
189
|
): T {
|
|
92
|
-
const
|
|
190
|
+
const mark = markSection(label);
|
|
93
191
|
try {
|
|
94
192
|
const result = fn();
|
|
95
|
-
const elapsedMs =
|
|
193
|
+
const elapsedMs = endSection(mark);
|
|
96
194
|
// Build `detail` only when actually reporting — the section runs on hot
|
|
97
195
|
// query paths, so the thunk must not allocate on the sub-threshold path.
|
|
98
196
|
if (elapsedMs >= SLOW_SYNC_THRESHOLD_MS) {
|
|
@@ -100,7 +198,7 @@ export function timeSyncSection<T>(
|
|
|
100
198
|
}
|
|
101
199
|
return result;
|
|
102
200
|
} catch (err) {
|
|
103
|
-
reportSlowSync(label,
|
|
201
|
+
reportSlowSync(label, endSection(mark));
|
|
104
202
|
throw err;
|
|
105
203
|
}
|
|
106
204
|
}
|
|
@@ -87,6 +87,13 @@ interface WakeConversationProbe {
|
|
|
87
87
|
* persistent `setTrustContext`) and restores the prior value in its finally.
|
|
88
88
|
*/
|
|
89
89
|
turnTrustContextSets: Array<{ ctx: unknown; order: number }>;
|
|
90
|
+
/**
|
|
91
|
+
* `setTrustContext` writes to the persistent `conversation.trustContext`,
|
|
92
|
+
* in order. A trust-carrying wake's resolver leaves its trust here; the
|
|
93
|
+
* wake must put the prior value back so it doesn't linger for a later
|
|
94
|
+
* no-trust wake.
|
|
95
|
+
*/
|
|
96
|
+
trustContextSets: unknown[];
|
|
90
97
|
/**
|
|
91
98
|
* Every assignment to `conversation.wakePersonaOverride`, in order. A
|
|
92
99
|
* wake that applies an override records `[override, undefined]` — the
|
|
@@ -340,6 +347,10 @@ import type {
|
|
|
340
347
|
AgentLoopRunResult,
|
|
341
348
|
} from "../../agent/loop.js";
|
|
342
349
|
import type { Conversation } from "../../daemon/conversation.js";
|
|
350
|
+
import {
|
|
351
|
+
deleteConversation,
|
|
352
|
+
setConversation,
|
|
353
|
+
} from "../../daemon/conversation-registry.js";
|
|
343
354
|
import { ContextOverflowError, type Message } from "../../providers/types.js";
|
|
344
355
|
import {
|
|
345
356
|
__resetWakeChainForTests,
|
|
@@ -387,6 +398,8 @@ function makeWakeConversation(options: {
|
|
|
387
398
|
* (always under the mocked 200k window).
|
|
388
399
|
*/
|
|
389
400
|
estimatedInputTokens?: number;
|
|
401
|
+
/** Seed for the conversation's resting `trustContext`. */
|
|
402
|
+
initialTrustContext?: unknown;
|
|
390
403
|
}): WakeConversation {
|
|
391
404
|
const conversationId = options.conversationId ?? "conv-test";
|
|
392
405
|
const probe: WakeConversationProbe = {
|
|
@@ -401,6 +414,7 @@ function makeWakeConversation(options: {
|
|
|
401
414
|
processingDuringDrain: [],
|
|
402
415
|
allowedToolSnapshots: [],
|
|
403
416
|
turnTrustContextSets: [],
|
|
417
|
+
trustContextSets: [],
|
|
404
418
|
personaOverrideSets: [],
|
|
405
419
|
persistedAtEachEmit: [],
|
|
406
420
|
maybeCompactOrders: [],
|
|
@@ -413,6 +427,7 @@ function makeWakeConversation(options: {
|
|
|
413
427
|
let activeAllowedTools = options.initialAllowedTools;
|
|
414
428
|
let wakePersonaOverride: unknown;
|
|
415
429
|
let currentTurnTrustContext: unknown;
|
|
430
|
+
let persistentTrustContext: unknown = options.initialTrustContext;
|
|
416
431
|
const snapshotAllowedTools = (): string[] | undefined =>
|
|
417
432
|
activeAllowedTools ? [...activeAllowedTools].sort() : undefined;
|
|
418
433
|
|
|
@@ -526,7 +541,14 @@ function makeWakeConversation(options: {
|
|
|
526
541
|
},
|
|
527
542
|
getTurnChannelContext: () => null,
|
|
528
543
|
getTurnInterfaceContext: () => null,
|
|
529
|
-
trustContext
|
|
544
|
+
get trustContext() {
|
|
545
|
+
return persistentTrustContext;
|
|
546
|
+
},
|
|
547
|
+
// Mirrors Conversation.setTrustContext (coerces null → undefined).
|
|
548
|
+
setTrustContext(ctx: unknown) {
|
|
549
|
+
persistentTrustContext = ctx ?? undefined;
|
|
550
|
+
probe.trustContextSets.push(ctx);
|
|
551
|
+
},
|
|
530
552
|
buildCurrentSystemPrompt: () => "mock-system-prompt",
|
|
531
553
|
modelOverride: undefined,
|
|
532
554
|
...(drainQueue ? { drainQueue } : {}),
|
|
@@ -1535,6 +1557,141 @@ describe("wakeAgentForOpportunity", () => {
|
|
|
1535
1557
|
expect(conversation.currentTurnTrustContext).toBeUndefined();
|
|
1536
1558
|
});
|
|
1537
1559
|
|
|
1560
|
+
// ── Persistent-trust restore ────────────────────────────────────────
|
|
1561
|
+
// The resolver leaves the wake's trust on the conversation. The wake must
|
|
1562
|
+
// put the prior resting value back, or a later no-trust wake inherits it
|
|
1563
|
+
// through tool setup's `currentTurnTrustContext ?? trustContext` fallback.
|
|
1564
|
+
|
|
1565
|
+
const GUARDIAN_TRUST = {
|
|
1566
|
+
sourceChannel: "vellum",
|
|
1567
|
+
trustClass: "guardian",
|
|
1568
|
+
} as const;
|
|
1569
|
+
|
|
1570
|
+
// The wake reads the prior trust from the live registry, so a test that
|
|
1571
|
+
// wants to exercise the restore registers its double there and simulates
|
|
1572
|
+
// the resolver's write by setting the trust in resolveTarget.
|
|
1573
|
+
const withRegisteredConversation = async (
|
|
1574
|
+
conversation: WakeConversation,
|
|
1575
|
+
run: () => Promise<unknown>,
|
|
1576
|
+
): Promise<void> => {
|
|
1577
|
+
setConversation(conversation.conversationId, conversation as Conversation);
|
|
1578
|
+
try {
|
|
1579
|
+
await run();
|
|
1580
|
+
} finally {
|
|
1581
|
+
deleteConversation(conversation.conversationId);
|
|
1582
|
+
}
|
|
1583
|
+
};
|
|
1584
|
+
|
|
1585
|
+
test("restores the conversation's prior trust once the wake ends", async () => {
|
|
1586
|
+
const priorTrust = {
|
|
1587
|
+
sourceChannel: "slack",
|
|
1588
|
+
trustClass: "trusted_contact",
|
|
1589
|
+
} as const;
|
|
1590
|
+
const conversation = makeWakeConversation({
|
|
1591
|
+
conversationId: "conv-trust-restore",
|
|
1592
|
+
initialTrustContext: priorTrust,
|
|
1593
|
+
});
|
|
1594
|
+
|
|
1595
|
+
await withRegisteredConversation(conversation, () =>
|
|
1596
|
+
wakeAgentForOpportunity(
|
|
1597
|
+
{
|
|
1598
|
+
conversationId: "conv-trust-restore",
|
|
1599
|
+
hint: "x",
|
|
1600
|
+
source: "t",
|
|
1601
|
+
trustContext: GUARDIAN_TRUST,
|
|
1602
|
+
},
|
|
1603
|
+
{
|
|
1604
|
+
resolveTarget: async () => {
|
|
1605
|
+
conversation.setTrustContext(GUARDIAN_TRUST);
|
|
1606
|
+
return conversation;
|
|
1607
|
+
},
|
|
1608
|
+
},
|
|
1609
|
+
),
|
|
1610
|
+
);
|
|
1611
|
+
|
|
1612
|
+
// Resolver installs guardian, wake restores the prior value.
|
|
1613
|
+
expect(conversation.trustContextSets).toEqual([GUARDIAN_TRUST, priorTrust]);
|
|
1614
|
+
expect(conversation.trustContext).toEqual(priorTrust);
|
|
1615
|
+
});
|
|
1616
|
+
|
|
1617
|
+
test("restores the prior trust even when the agent loop throws", async () => {
|
|
1618
|
+
const conversation = makeWakeConversation({
|
|
1619
|
+
conversationId: "conv-trust-restore-throw",
|
|
1620
|
+
runImpl: async () => {
|
|
1621
|
+
throw new Error("boom");
|
|
1622
|
+
},
|
|
1623
|
+
});
|
|
1624
|
+
|
|
1625
|
+
await withRegisteredConversation(conversation, () =>
|
|
1626
|
+
wakeAgentForOpportunity(
|
|
1627
|
+
{
|
|
1628
|
+
conversationId: "conv-trust-restore-throw",
|
|
1629
|
+
hint: "x",
|
|
1630
|
+
source: "t",
|
|
1631
|
+
trustContext: GUARDIAN_TRUST,
|
|
1632
|
+
},
|
|
1633
|
+
{
|
|
1634
|
+
resolveTarget: async () => {
|
|
1635
|
+
conversation.setTrustContext(GUARDIAN_TRUST);
|
|
1636
|
+
return conversation;
|
|
1637
|
+
},
|
|
1638
|
+
},
|
|
1639
|
+
),
|
|
1640
|
+
);
|
|
1641
|
+
|
|
1642
|
+
// Nothing was resting before the wake, so it goes back to unset.
|
|
1643
|
+
expect(conversation.trustContext).toBeUndefined();
|
|
1644
|
+
});
|
|
1645
|
+
|
|
1646
|
+
test("leaves a trust that was re-set mid-run alone (identity guard)", async () => {
|
|
1647
|
+
const replaced = {
|
|
1648
|
+
sourceChannel: "vellum",
|
|
1649
|
+
trustClass: "unknown",
|
|
1650
|
+
} as const;
|
|
1651
|
+
const conversation = makeWakeConversation({
|
|
1652
|
+
conversationId: "conv-trust-guard",
|
|
1653
|
+
runImpl: async (input) => {
|
|
1654
|
+
conversation.setTrustContext(replaced);
|
|
1655
|
+
return runResult(input);
|
|
1656
|
+
},
|
|
1657
|
+
});
|
|
1658
|
+
|
|
1659
|
+
await withRegisteredConversation(conversation, () =>
|
|
1660
|
+
wakeAgentForOpportunity(
|
|
1661
|
+
{
|
|
1662
|
+
conversationId: "conv-trust-guard",
|
|
1663
|
+
hint: "x",
|
|
1664
|
+
source: "t",
|
|
1665
|
+
trustContext: GUARDIAN_TRUST,
|
|
1666
|
+
},
|
|
1667
|
+
{
|
|
1668
|
+
resolveTarget: async () => {
|
|
1669
|
+
conversation.setTrustContext(GUARDIAN_TRUST);
|
|
1670
|
+
return conversation;
|
|
1671
|
+
},
|
|
1672
|
+
},
|
|
1673
|
+
),
|
|
1674
|
+
);
|
|
1675
|
+
|
|
1676
|
+
// The wake sees a different reference than it installed, so it doesn't
|
|
1677
|
+
// restore: two writes (resolver install, mid-run replacement), no third.
|
|
1678
|
+
expect(conversation.trustContext).toEqual(replaced);
|
|
1679
|
+
expect(conversation.trustContextSets).toHaveLength(2);
|
|
1680
|
+
});
|
|
1681
|
+
|
|
1682
|
+
test("never touches the persistent trust when the wake carries none", async () => {
|
|
1683
|
+
const conversation = makeWakeConversation({
|
|
1684
|
+
conversationId: "conv-trust-none",
|
|
1685
|
+
});
|
|
1686
|
+
|
|
1687
|
+
await wakeAgentForOpportunity(
|
|
1688
|
+
{ conversationId: "conv-trust-none", hint: "x", source: "t" },
|
|
1689
|
+
{ resolveTarget: async () => conversation },
|
|
1690
|
+
);
|
|
1691
|
+
|
|
1692
|
+
expect(conversation.trustContextSets).toHaveLength(0);
|
|
1693
|
+
});
|
|
1694
|
+
|
|
1538
1695
|
test("two concurrent wakes on the same conversation are serialized", async () => {
|
|
1539
1696
|
// Build a target whose agentLoop.run resolves only when we signal.
|
|
1540
1697
|
const gate1 = Promise.withResolvers<void>();
|
|
@@ -619,6 +619,18 @@ export async function wakeAgentForOpportunity(
|
|
|
619
619
|
const startedAt = nowFn();
|
|
620
620
|
|
|
621
621
|
return runSingleFlight(conversationId, async () => {
|
|
622
|
+
// Snapshot the conversation's resting trust before the resolver runs, so
|
|
623
|
+
// it can be restored after. The resolver leaves the wake's trust on the
|
|
624
|
+
// conversation, and a following no-trust wake would otherwise read it via
|
|
625
|
+
// tool setup's `currentTurnTrustContext ?? trustContext` fallback. Null
|
|
626
|
+
// when the conversation isn't resident yet (a fresh hydrate or a fork).
|
|
627
|
+
let priorPersistentTrust: TrustContext | null = null;
|
|
628
|
+
if (opts.trustContext) {
|
|
629
|
+
const { findConversation } =
|
|
630
|
+
await import("../daemon/conversation-registry.js");
|
|
631
|
+
priorPersistentTrust =
|
|
632
|
+
findConversation(conversationId)?.trustContext ?? null;
|
|
633
|
+
}
|
|
622
634
|
const resolved = await resolveTarget(opts);
|
|
623
635
|
if (resolved === "archived") {
|
|
624
636
|
log.info(
|
|
@@ -640,6 +652,18 @@ export async function wakeAgentForOpportunity(
|
|
|
640
652
|
}
|
|
641
653
|
const conversation = resolved;
|
|
642
654
|
|
|
655
|
+
// Put the resting trust back on exit. The guard restores only our own
|
|
656
|
+
// elevation, so a trust re-set by another turn is left alone; it's also
|
|
657
|
+
// idempotent, so the several call sites below are safe.
|
|
658
|
+
const restorePersistentWakeTrust = (): void => {
|
|
659
|
+
if (
|
|
660
|
+
opts.trustContext &&
|
|
661
|
+
conversation.trustContext === opts.trustContext
|
|
662
|
+
) {
|
|
663
|
+
conversation.setTrustContext(priorPersistentTrust);
|
|
664
|
+
}
|
|
665
|
+
};
|
|
666
|
+
|
|
643
667
|
const { decision: diskPressureDecision, status: diskPressureStatus } =
|
|
644
668
|
classifyWakeDiskPressurePolicy(opts);
|
|
645
669
|
if (diskPressureDecision.action === "block") {
|
|
@@ -657,6 +681,7 @@ export async function wakeAgentForOpportunity(
|
|
|
657
681
|
},
|
|
658
682
|
"agent-wake: blocked by disk pressure cleanup mode",
|
|
659
683
|
);
|
|
684
|
+
restorePersistentWakeTrust();
|
|
660
685
|
return {
|
|
661
686
|
invoked: false,
|
|
662
687
|
producedToolCalls: false,
|
|
@@ -670,6 +695,7 @@ export async function wakeAgentForOpportunity(
|
|
|
670
695
|
{ conversationId, source },
|
|
671
696
|
"agent-wake: conversation still processing after timeout; skipping",
|
|
672
697
|
);
|
|
698
|
+
restorePersistentWakeTrust();
|
|
673
699
|
return { invoked: false, producedToolCalls: false, reason: "timeout" };
|
|
674
700
|
}
|
|
675
701
|
|
|
@@ -1424,6 +1450,8 @@ export async function wakeAgentForOpportunity(
|
|
|
1424
1450
|
|
|
1425
1451
|
return { invoked: true, producedToolCalls };
|
|
1426
1452
|
} finally {
|
|
1453
|
+
// Put the conversation's resting trust back on every exit path.
|
|
1454
|
+
restorePersistentWakeTrust();
|
|
1427
1455
|
// The success path (above) already called setProcessing(false)
|
|
1428
1456
|
// + drainQueue after tail persist. This catch-all handles the
|
|
1429
1457
|
// error and early-return paths where no tail was produced — those
|
package/src/util/platform.ts
CHANGED
|
@@ -348,6 +348,17 @@ export function getWorkspaceRoutesDir(): string {
|
|
|
348
348
|
return join(getWorkspaceDir(), "routes");
|
|
349
349
|
}
|
|
350
350
|
|
|
351
|
+
/**
|
|
352
|
+
* Returns $VELLUM_WORKSPACE_DIR/workflows — saved (named) workflow scripts.
|
|
353
|
+
*
|
|
354
|
+
* A file here becomes a saved workflow whose source is executed (in the sandbox,
|
|
355
|
+
* and unattended when triggered by a schedule), so the file risk classifier
|
|
356
|
+
* escalates writes under this path to High like `tools/` and `routes/`.
|
|
357
|
+
*/
|
|
358
|
+
export function getWorkspaceWorkflowsDir(): string {
|
|
359
|
+
return join(getWorkspaceDir(), "workflows");
|
|
360
|
+
}
|
|
361
|
+
|
|
351
362
|
/** Returns $VELLUM_WORKSPACE_DIR/deprecated — transitional files slated for removal. */
|
|
352
363
|
export function getDeprecatedDir(): string {
|
|
353
364
|
return join(getWorkspaceDir(), "deprecated");
|
|
@@ -218,8 +218,8 @@ describe("getWorkflow", () => {
|
|
|
218
218
|
});
|
|
219
219
|
});
|
|
220
220
|
|
|
221
|
-
describe("name collisions", () => {
|
|
222
|
-
test("a
|
|
221
|
+
describe("name collisions (fail closed)", () => {
|
|
222
|
+
test("a base-name collision (dir + flat) resolves NEITHER", () => {
|
|
223
223
|
writeWorkflow(
|
|
224
224
|
"foo.workflow.ts",
|
|
225
225
|
`export const meta = { name: "foo", description: "flat" };\nreturn "FLAT";`,
|
|
@@ -229,16 +229,12 @@ describe("name collisions", () => {
|
|
|
229
229
|
`export const meta = { name: "foo", description: "dir" };\nreturn "DIR";`,
|
|
230
230
|
);
|
|
231
231
|
|
|
232
|
-
|
|
233
|
-
expect(
|
|
234
|
-
expect(
|
|
235
|
-
|
|
236
|
-
const foos = listWorkflows().filter((e) => e.name === "foo");
|
|
237
|
-
expect(foos).toHaveLength(1);
|
|
238
|
-
expect(foos[0]!.description).toBe("dir");
|
|
232
|
+
// Neither the base name nor the (shared) meta.name resolves.
|
|
233
|
+
expect(getWorkflow("foo")).toBeNull();
|
|
234
|
+
expect(listWorkflows().filter((e) => e.name === "foo")).toHaveLength(0);
|
|
239
235
|
});
|
|
240
236
|
|
|
241
|
-
test("
|
|
237
|
+
test("a base-name collision hides both sides' own meta.names", () => {
|
|
242
238
|
writeWorkflow(
|
|
243
239
|
"bar.workflow.ts",
|
|
244
240
|
`export const meta = { name: "flat-name", description: "flat" };\nreturn "FLAT";`,
|
|
@@ -248,14 +244,33 @@ describe("name collisions", () => {
|
|
|
248
244
|
`export const meta = { name: "dir-name", description: "dir" };\nreturn "DIR";`,
|
|
249
245
|
);
|
|
250
246
|
|
|
251
|
-
expect(getWorkflow("dir-name")
|
|
247
|
+
expect(getWorkflow("dir-name")).toBeNull();
|
|
252
248
|
expect(getWorkflow("flat-name")).toBeNull();
|
|
253
|
-
|
|
254
|
-
expect(
|
|
255
|
-
|
|
249
|
+
expect(getWorkflow("bar")).toBeNull();
|
|
250
|
+
expect(listWorkflows()).toEqual([]);
|
|
251
|
+
});
|
|
252
|
+
|
|
253
|
+
test("a base-name collision does not affect unrelated workflows", () => {
|
|
254
|
+
writeWorkflow(
|
|
255
|
+
"foo.workflow.ts",
|
|
256
|
+
`export const meta = { name: "foo", description: "flat" };\nreturn "FLAT";`,
|
|
257
|
+
);
|
|
258
|
+
writeDirWorkflow(
|
|
259
|
+
"foo",
|
|
260
|
+
`export const meta = { name: "foo", description: "dir" };\nreturn "DIR";`,
|
|
261
|
+
);
|
|
262
|
+
// A separate, non-colliding workflow still resolves normally.
|
|
263
|
+
writeWorkflow(
|
|
264
|
+
"safe.workflow.ts",
|
|
265
|
+
`export const meta = { name: "safe", description: "ok" };\nreturn "SAFE";`,
|
|
266
|
+
);
|
|
267
|
+
|
|
268
|
+
expect(getWorkflow("safe")!.source).toContain("SAFE");
|
|
269
|
+
expect(listWorkflows().map((e) => e.name)).toEqual(["safe"]);
|
|
256
270
|
});
|
|
257
271
|
|
|
258
|
-
test("
|
|
272
|
+
test("a duplicate meta.name across different files resolves NEITHER", () => {
|
|
273
|
+
// Distinct base names, same meta.name → fail closed (no hijack by order).
|
|
259
274
|
writeWorkflow(
|
|
260
275
|
"a.workflow.ts",
|
|
261
276
|
`export const meta = { name: "dup", description: "from-a" };\nreturn "A";`,
|
|
@@ -265,10 +280,10 @@ describe("name collisions", () => {
|
|
|
265
280
|
`export const meta = { name: "dup", description: "from-b" };\nreturn "B";`,
|
|
266
281
|
);
|
|
267
282
|
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
expect(
|
|
272
|
-
expect(getWorkflow("
|
|
283
|
+
expect(getWorkflow("dup")).toBeNull();
|
|
284
|
+
expect(listWorkflows().filter((e) => e.name === "dup")).toHaveLength(0);
|
|
285
|
+
// Each file is still reachable by its unambiguous base name.
|
|
286
|
+
expect(getWorkflow("a")!.source).toContain("A");
|
|
287
|
+
expect(getWorkflow("b")!.source).toContain("B");
|
|
273
288
|
});
|
|
274
289
|
});
|
package/src/workflows/library.ts
CHANGED
|
@@ -4,9 +4,10 @@
|
|
|
4
4
|
*
|
|
5
5
|
* Saved workflows live at `<workspace>/workflows/`. The preferred layout is
|
|
6
6
|
* directory-style `<name>/workflow.ts` (so a workflow and its state can sit in
|
|
7
|
-
* one folder); flat `<name>.workflow.ts` is still supported but discouraged.
|
|
8
|
-
*
|
|
9
|
-
*
|
|
7
|
+
* one folder); flat `<name>.workflow.ts` is still supported but discouraged. A
|
|
8
|
+
* base-name collision or a duplicate `meta.name` FAILS CLOSED — the ambiguous
|
|
9
|
+
* name resolves to nothing, so a planted file can't shadow a trusted workflow.
|
|
10
|
+
* Each is a normal workflow script: a leading literal
|
|
10
11
|
* `export const meta = { name, description }` followed by the script body. The
|
|
11
12
|
* library only reads the STATIC `meta` (via {@link extractWorkflowMeta}, a
|
|
12
13
|
* pure-literal extractor that never executes the untrusted source — only the
|
|
@@ -22,7 +23,7 @@ import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
|
22
23
|
import { join } from "node:path";
|
|
23
24
|
|
|
24
25
|
import { getLogger } from "../util/logger.js";
|
|
25
|
-
import {
|
|
26
|
+
import { getWorkspaceWorkflowsDir } from "../util/platform.js";
|
|
26
27
|
import { extractWorkflowMeta, type WorkflowMeta } from "./engine.js";
|
|
27
28
|
|
|
28
29
|
const log = getLogger("workflow-library");
|
|
@@ -48,11 +49,6 @@ export interface SavedWorkflowSource {
|
|
|
48
49
|
path: string;
|
|
49
50
|
}
|
|
50
51
|
|
|
51
|
-
/** Absolute path to the saved-workflows directory (`<workspace>/workflows`). */
|
|
52
|
-
function workflowsDir(): string {
|
|
53
|
-
return join(getWorkspaceDir(), "workflows");
|
|
54
|
-
}
|
|
55
|
-
|
|
56
52
|
/** Filename of the entry-point script inside a directory-style workflow. */
|
|
57
53
|
const DIRECTORY_ENTRY = "workflow.ts";
|
|
58
54
|
|
|
@@ -69,66 +65,90 @@ interface RawWorkflowFile {
|
|
|
69
65
|
source: string;
|
|
70
66
|
}
|
|
71
67
|
|
|
68
|
+
/** Read one saved workflow off disk; `null` (with a warning) if unreadable. */
|
|
69
|
+
function readRawWorkflow(
|
|
70
|
+
baseName: string,
|
|
71
|
+
path: string,
|
|
72
|
+
): RawWorkflowFile | null {
|
|
73
|
+
try {
|
|
74
|
+
return { baseName, path, source: readFileSync(path, "utf8") };
|
|
75
|
+
} catch (err) {
|
|
76
|
+
log.warn({ err, path }, "Failed to read saved workflow; skipping");
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Log the fail-closed refusal to resolve a name declared by multiple files. */
|
|
82
|
+
function logDuplicateMetaName(name: string, paths: string[]): void {
|
|
83
|
+
log.error(
|
|
84
|
+
{ name, paths },
|
|
85
|
+
`Multiple saved workflows declare meta.name "${name}"; resolving none. ` +
|
|
86
|
+
`Delete or rename all but one to disambiguate.`,
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
|
|
72
90
|
/**
|
|
73
|
-
* Yield every readable saved workflow in a STABLE order (the
|
|
74
|
-
*
|
|
75
|
-
*
|
|
76
|
-
*
|
|
77
|
-
*
|
|
78
|
-
*
|
|
91
|
+
* Yield every readable saved workflow in a STABLE order (sorted, so "the first
|
|
92
|
+
* match" is deterministic). Directory-style `<name>/workflow.ts` is yielded
|
|
93
|
+
* before flat `<name>.workflow.ts`.
|
|
94
|
+
*
|
|
95
|
+
* FAIL CLOSED on a base-name collision: if a base name exists as BOTH a
|
|
96
|
+
* directory and a flat file, neither is yielded — otherwise a planted
|
|
97
|
+
* `<name>/workflow.ts` could silently shadow a trusted flat workflow.
|
|
98
|
+
*
|
|
99
|
+
* Yields nothing if the directory does not exist. An unreadable entry is
|
|
100
|
+
* skipped with a logged warning.
|
|
79
101
|
*/
|
|
80
102
|
function* readWorkflowFiles(): Generator<RawWorkflowFile> {
|
|
81
|
-
const dir =
|
|
103
|
+
const dir = getWorkspaceWorkflowsDir();
|
|
82
104
|
if (!existsSync(dir)) return;
|
|
83
105
|
const entries = readdirSync(dir).sort();
|
|
84
|
-
const seen = new Set<string>();
|
|
85
106
|
|
|
86
|
-
//
|
|
107
|
+
// Resolve each form once, keyed by base name (sorted entries keep Map
|
|
108
|
+
// iteration deterministic).
|
|
109
|
+
const dirPaths = new Map<string, string>();
|
|
110
|
+
const flatPaths = new Map<string, string>();
|
|
87
111
|
for (const entry of entries) {
|
|
88
|
-
if (entry.endsWith(WORKFLOW_SUFFIX))
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
try {
|
|
92
|
-
const source = readFileSync(path, "utf8");
|
|
93
|
-
seen.add(entry);
|
|
94
|
-
yield { baseName: entry, path, source };
|
|
95
|
-
} catch (err) {
|
|
96
|
-
log.warn({ err, path }, "Failed to read saved workflow; skipping");
|
|
112
|
+
if (entry.endsWith(WORKFLOW_SUFFIX)) {
|
|
113
|
+
flatPaths.set(fileBaseName(entry), join(dir, entry));
|
|
114
|
+
continue;
|
|
97
115
|
}
|
|
116
|
+
const entrypoint = join(dir, entry, DIRECTORY_ENTRY);
|
|
117
|
+
if (existsSync(entrypoint)) dirPaths.set(entry, entrypoint);
|
|
98
118
|
}
|
|
99
119
|
|
|
100
|
-
//
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
}
|
|
120
|
+
// Fail closed on a base-name collision (both forms present).
|
|
121
|
+
const collisions = new Set<string>();
|
|
122
|
+
for (const baseName of dirPaths.keys()) {
|
|
123
|
+
if (flatPaths.has(baseName)) collisions.add(baseName);
|
|
124
|
+
}
|
|
125
|
+
for (const baseName of collisions) {
|
|
126
|
+
log.error(
|
|
127
|
+
{ dir, baseName },
|
|
128
|
+
`Saved workflow "${baseName}" exists as BOTH a directory "${baseName}/" and ` +
|
|
129
|
+
`a flat file "${baseName}${WORKFLOW_SUFFIX}"; resolving neither. Delete one to disambiguate.`,
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// Directory-style first, then flat; a colliding base name is skipped in both.
|
|
134
|
+
for (const [baseName, path] of [...dirPaths, ...flatPaths]) {
|
|
135
|
+
if (collisions.has(baseName)) continue;
|
|
136
|
+
const raw = readRawWorkflow(baseName, path);
|
|
137
|
+
if (raw) yield raw;
|
|
119
138
|
}
|
|
120
139
|
}
|
|
121
140
|
|
|
122
141
|
/**
|
|
123
|
-
* List every saved workflow with a statically-extractable `meta
|
|
124
|
-
*
|
|
125
|
-
*
|
|
126
|
-
*
|
|
127
|
-
*
|
|
142
|
+
* List every saved workflow with a statically-extractable `meta` (a file whose
|
|
143
|
+
* `meta` can't be extracted is skipped, not fatal).
|
|
144
|
+
*
|
|
145
|
+
* FAIL CLOSED on a duplicate `meta.name`: if two files declare the same name,
|
|
146
|
+
* neither is listed — matching {@link getWorkflow}, so a planted file can't
|
|
147
|
+
* hijack the name by iteration order.
|
|
128
148
|
*/
|
|
129
149
|
export function listWorkflows(): SavedWorkflowEntry[] {
|
|
130
|
-
|
|
131
|
-
const
|
|
150
|
+
// Group by meta.name so a duplicate can drop all sharers (fail closed).
|
|
151
|
+
const byName = new Map<string, SavedWorkflowEntry[]>();
|
|
132
152
|
for (const { path, source } of readWorkflowFiles()) {
|
|
133
153
|
let meta: WorkflowMeta;
|
|
134
154
|
try {
|
|
@@ -140,32 +160,43 @@ export function listWorkflows(): SavedWorkflowEntry[] {
|
|
|
140
160
|
);
|
|
141
161
|
continue;
|
|
142
162
|
}
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
163
|
+
const group = byName.get(meta.name) ?? [];
|
|
164
|
+
group.push({ name: meta.name, description: meta.description, path });
|
|
165
|
+
byName.set(meta.name, group);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const entries: SavedWorkflowEntry[] = [];
|
|
169
|
+
for (const [name, group] of byName) {
|
|
170
|
+
if (group.length > 1) {
|
|
171
|
+
logDuplicateMetaName(
|
|
172
|
+
name,
|
|
173
|
+
group.map((e) => e.path),
|
|
147
174
|
);
|
|
148
175
|
continue;
|
|
149
176
|
}
|
|
150
|
-
|
|
151
|
-
entries.push({ name: meta.name, description: meta.description, path });
|
|
177
|
+
entries.push(group[0]);
|
|
152
178
|
}
|
|
153
179
|
return entries;
|
|
154
180
|
}
|
|
155
181
|
|
|
156
182
|
/**
|
|
157
|
-
* Resolve a saved workflow by name
|
|
158
|
-
*
|
|
159
|
-
*
|
|
160
|
-
*
|
|
161
|
-
*
|
|
183
|
+
* Resolve a saved workflow by name: `meta.name` first (canonical), then the
|
|
184
|
+
* base name (directory or flat file). Returns the source + path, or `null`.
|
|
185
|
+
*
|
|
186
|
+
* FAIL CLOSED on a duplicate `meta.name`: if two files declare the requested
|
|
187
|
+
* name, neither is returned, so a planted file can't hijack it by iteration
|
|
188
|
+
* order. Base-name collisions already fail closed in {@link readWorkflowFiles}.
|
|
162
189
|
*/
|
|
163
190
|
export function getWorkflow(name: string): SavedWorkflowSource | null {
|
|
191
|
+
const nameMatches: SavedWorkflowSource[] = [];
|
|
164
192
|
let fileMatch: SavedWorkflowSource | null = null;
|
|
165
193
|
for (const { baseName, path, source } of readWorkflowFiles()) {
|
|
166
194
|
// Prefer a `meta.name` match — it is the canonical identity.
|
|
167
195
|
try {
|
|
168
|
-
if (extractWorkflowMeta(source).name === name)
|
|
196
|
+
if (extractWorkflowMeta(source).name === name) {
|
|
197
|
+
nameMatches.push({ source, path });
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
169
200
|
} catch {
|
|
170
201
|
// Fall through: a file with non-extractable meta can still match by name.
|
|
171
202
|
}
|
|
@@ -174,5 +205,13 @@ export function getWorkflow(name: string): SavedWorkflowSource | null {
|
|
|
174
205
|
fileMatch = { source, path };
|
|
175
206
|
}
|
|
176
207
|
}
|
|
177
|
-
|
|
208
|
+
|
|
209
|
+
if (nameMatches.length > 1) {
|
|
210
|
+
logDuplicateMetaName(
|
|
211
|
+
name,
|
|
212
|
+
nameMatches.map((m) => m.path),
|
|
213
|
+
);
|
|
214
|
+
return null;
|
|
215
|
+
}
|
|
216
|
+
return nameMatches[0] ?? fileMatch;
|
|
178
217
|
}
|