minimal-agent 0.18.20 → 0.18.22

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.
Files changed (188) hide show
  1. package/README.md +16 -3
  2. package/package.json +1 -1
  3. package/plugins/cron-runner/README.md +23 -0
  4. package/plugins/cron-runner/commands/cron.md +7 -1
  5. package/plugins/cron-runner/plugin.js +9 -2
  6. package/plugins/cron-runner/plugin.ts +10 -2
  7. package/plugins/cron-runner/src/commands.js +112 -25
  8. package/plugins/cron-runner/src/commands.ts +154 -33
  9. package/plugins/cron-runner/src/contract.js +70 -0
  10. package/plugins/cron-runner/src/contract.ts +70 -0
  11. package/plugins/cron-runner/src/requests.js +22 -13
  12. package/plugins/cron-runner/src/requests.ts +34 -14
  13. package/plugins/cron-runner/src/runs.js +63 -10
  14. package/plugins/cron-runner/src/runs.ts +107 -15
  15. package/plugins/cron-runner/src/scheduler.js +188 -76
  16. package/plugins/cron-runner/src/scheduler.ts +277 -94
  17. package/plugins/cron-runner/src/schema.js +52 -17
  18. package/plugins/cron-runner/src/schema.ts +73 -22
  19. package/plugins/cron-runner/src/service.js +29 -8
  20. package/plugins/cron-runner/src/service.ts +71 -18
  21. package/plugins/cron-runner/src/store.js +92 -30
  22. package/plugins/cron-runner/src/store.ts +156 -53
  23. package/plugins/cron-runner/src/transaction.js +24 -0
  24. package/plugins/cron-runner/src/transaction.ts +36 -0
  25. package/plugins/cron-runner/src/types.ts +30 -4
  26. package/plugins/cron-runner/test/lifecycle.test.ts +419 -0
  27. package/plugins/cron-runner/test/plugin-integration.test.ts +3 -2
  28. package/plugins/cron-runner/test/reliability.test.ts +2 -2
  29. package/plugins/cron-runner/test/store-and-scheduler.test.ts +9 -7
  30. package/plugins/workflow-runner/plugin.js +1 -0
  31. package/plugins/workflow-runner/plugin.ts +1 -0
  32. package/plugins/workflow-runner/src/index.js +1 -0
  33. package/plugins/workflow-runner/src/index.ts +2 -0
  34. package/plugins/workflow-runner/src/runner.js +6 -1
  35. package/plugins/workflow-runner/src/runner.ts +5 -1
  36. package/plugins/workflow-runner/src/types.ts +1 -0
  37. package/plugins/workflow-runner/test/api.test.ts +1 -0
  38. package/plugins/workflow-runner/test/apiCapabilities.test.ts +4 -0
  39. package/plugins/workflow-runner/test/apiConcurrencyGate.test.ts +1 -0
  40. package/plugins/workflow-runner/test/childWorkflow.test.ts +19 -0
  41. package/plugins/workflow-runner/test/embeddedExecution.test.ts +23 -3
  42. package/src/advisor/README.md +17 -6
  43. package/src/advisor/advisorNudge.js +23 -3
  44. package/src/advisor/advisorNudge.ts +20 -3
  45. package/src/advisor/deliveryReview.js +9 -2
  46. package/src/advisor/deliveryReview.ts +10 -2
  47. package/src/cli/args.js +1 -0
  48. package/src/cli/args.ts +1 -0
  49. package/src/cli/headlessTurn.js +143 -0
  50. package/src/cli/headlessTurn.ts +187 -0
  51. package/src/cli/lifecycle.js +52 -0
  52. package/src/cli/lifecycle.ts +59 -0
  53. package/src/cli/print.js +91 -240
  54. package/src/cli/print.ts +99 -301
  55. package/src/cli/quickModelSetup.js +3 -0
  56. package/src/cli/quickModelSetup.tsx +3 -0
  57. package/src/cli/streamJson.js +244 -334
  58. package/src/cli/streamJson.ts +248 -416
  59. package/src/cli/wizards/contextAdvisorWizard.js +0 -7
  60. package/src/cli/wizards/contextAdvisorWizard.tsx +0 -11
  61. package/src/cli/wizards/providerPresets.js +25 -14
  62. package/src/cli/wizards/providerPresets.ts +25 -14
  63. package/src/cli/wizards/providerWizard.js +29 -11
  64. package/src/cli/wizards/providerWizard.tsx +29 -11
  65. package/src/config/configDefaults.js +2 -2
  66. package/src/config/configDefaults.ts +2 -2
  67. package/src/config/configDiagnostics.js +7 -3
  68. package/src/config/configDiagnostics.ts +6 -3
  69. package/src/config/configFile.ts +1 -1
  70. package/src/context/compact.js +40 -10
  71. package/src/context/compact.ts +51 -12
  72. package/src/context/compactResources.js +39 -0
  73. package/src/context/compactResources.ts +35 -0
  74. package/src/context/manualCompact.js +20 -0
  75. package/src/context/manualCompact.ts +28 -0
  76. package/src/llm/client.js +4 -0
  77. package/src/llm/client.ts +4 -0
  78. package/src/llm/messageProvenance.js +1 -1
  79. package/src/llm/messageProvenance.ts +1 -1
  80. package/src/loop/README.md +4 -2
  81. package/src/loop/deliveryIntent.js +3 -2
  82. package/src/loop/deliveryIntent.ts +4 -2
  83. package/src/loop/messages.js +1 -0
  84. package/src/loop/messages.ts +1 -0
  85. package/src/loop/options.ts +2 -0
  86. package/src/loop.js +10 -2
  87. package/src/loop.ts +9 -2
  88. package/src/main.js +40 -45
  89. package/src/main.tsx +33 -52
  90. package/src/plugin-sdk.js +1 -1
  91. package/src/plugin-sdk.ts +1 -1
  92. package/src/plugins/artifactDelivery.js +76 -0
  93. package/src/plugins/artifactDelivery.ts +76 -0
  94. package/src/plugins/pluginApi.ts +4 -0
  95. package/src/plugins/pluginRunner.js +2 -0
  96. package/src/plugins/pluginRunner.ts +3 -0
  97. package/src/prompts/delegation.js +2 -2
  98. package/src/prompts/delegation.ts +2 -2
  99. package/src/prompts/policyRegistry.js +7 -5
  100. package/src/prompts/policyRegistry.ts +7 -5
  101. package/src/prompts/promptAssembly.js +2 -2
  102. package/src/prompts/promptAssembly.ts +2 -2
  103. package/src/runtime/requestIntent.js +86 -0
  104. package/src/runtime/requestIntent.ts +66 -0
  105. package/src/runtime/systemEvents.js +10 -1
  106. package/src/runtime/systemEvents.ts +9 -1
  107. package/src/session/commandTranscript.js +76 -0
  108. package/src/session/commandTranscript.ts +77 -0
  109. package/src/session/executionOutcome.js +25 -0
  110. package/src/session/executionOutcome.ts +34 -0
  111. package/src/session/runAgentTurn.js +8 -1
  112. package/src/session/runAgentTurn.ts +10 -1
  113. package/src/session/runTurn.js +40 -15
  114. package/src/session/runTurn.ts +38 -12
  115. package/src/session/sessionState.js +7 -2
  116. package/src/session/sessionState.ts +7 -2
  117. package/src/team/onlineToolContract.js +1 -0
  118. package/src/team/onlineToolContract.ts +1 -0
  119. package/src/tools/advisor/advisor.js +73 -30
  120. package/src/tools/advisor/advisor.ts +73 -33
  121. package/src/tools/advisor/advisorCoordination.js +44 -0
  122. package/src/tools/advisor/advisorCoordination.ts +45 -0
  123. package/src/tools/advisor/advisorDescription.js +1 -1
  124. package/src/tools/advisor/advisorDescription.ts +1 -1
  125. package/src/tools/agent/README.md +2 -0
  126. package/src/tools/agent/agent.js +7 -3
  127. package/src/tools/agent/agent.ts +7 -3
  128. package/src/tools/agent/agentHandoff.js +2 -1
  129. package/src/tools/agent/agentHandoff.ts +2 -1
  130. package/src/tools/agent/agentTaskService.js +26 -5
  131. package/src/tools/agent/agentTaskService.ts +25 -5
  132. package/src/tools/agent/agentTypes.js +2 -2
  133. package/src/tools/agent/agentTypes.ts +2 -2
  134. package/src/tools/agent/baselineAttach.js +14 -7
  135. package/src/tools/agent/baselineAttach.ts +14 -7
  136. package/src/tools/applypatch/applyPatch.js +39 -13
  137. package/src/tools/applypatch/applyPatch.ts +35 -15
  138. package/src/tools/bash/bash.js +3 -0
  139. package/src/tools/bash/bash.ts +3 -0
  140. package/src/tools/capabilities.js +1 -0
  141. package/src/tools/capabilities.ts +1 -0
  142. package/src/tools/download/download.js +147 -11
  143. package/src/tools/download/download.ts +193 -17
  144. package/src/tools/edit/edit.js +4 -4
  145. package/src/tools/edit/edit.ts +4 -4
  146. package/src/tools/edit/multi-edit.js +2 -2
  147. package/src/tools/edit/multi-edit.ts +2 -2
  148. package/src/tools/index.js +2 -0
  149. package/src/tools/index.ts +2 -0
  150. package/src/tools/powershell/powershell.js +2 -0
  151. package/src/tools/powershell/powershell.ts +2 -0
  152. package/src/tools/schedule/schedule.js +184 -0
  153. package/src/tools/schedule/schedule.ts +214 -0
  154. package/src/tools/shared/fileUtils.js +16 -6
  155. package/src/tools/shared/fileUtils.ts +15 -6
  156. package/src/tools/tasks/backgroundTaskService.js +108 -12
  157. package/src/tools/tasks/backgroundTaskService.ts +106 -14
  158. package/src/tools/tasks/taskOutput.js +15 -5
  159. package/src/tools/tasks/taskOutput.ts +13 -5
  160. package/src/tools/tasks/taskStop.js +2 -2
  161. package/src/tools/tasks/taskStop.ts +2 -2
  162. package/src/tools/toolPromptGuides.js +4 -3
  163. package/src/tools/toolPromptGuides.ts +4 -3
  164. package/src/tools/webfetch/webfetch.js +1 -1
  165. package/src/tools/webfetch/webfetch.ts +1 -1
  166. package/src/types.ts +6 -0
  167. package/src/ui/App.js +3 -1
  168. package/src/ui/App.tsx +2 -0
  169. package/src/ui/InputBox.js +2 -2
  170. package/src/ui/InputBox.tsx +2 -2
  171. package/src/ui/LiveArea.js +6 -1
  172. package/src/ui/LiveArea.tsx +6 -1
  173. package/src/ui/MessageList.js +2 -0
  174. package/src/ui/MessageList.tsx +2 -0
  175. package/src/ui/README.md +8 -2
  176. package/src/ui/activityPresentation.js +23 -3
  177. package/src/ui/activityPresentation.ts +22 -3
  178. package/src/ui/backgroundWake.js +20 -4
  179. package/src/ui/backgroundWake.ts +19 -4
  180. package/src/ui/commandTranscript.js +2 -69
  181. package/src/ui/commandTranscript.ts +2 -71
  182. package/src/ui/hooks/useBackgroundAgents.js +33 -0
  183. package/src/ui/hooks/useBackgroundAgents.ts +36 -0
  184. package/src/ui/hooks/useChat.js +46 -25
  185. package/src/ui/hooks/useChat.ts +36 -23
  186. package/src/web/protocol.ts +5 -2
  187. package/src/cli/wizards/advisorWizard.js +0 -152
  188. package/src/cli/wizards/advisorWizard.tsx +0 -203
@@ -0,0 +1,36 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+ import { createHash } from 'node:crypto';
3
+ import { join } from 'node:path';
4
+ import { withStoreLock } from './lock.js';
5
+
6
+ const held = new AsyncLocalStorage<ReadonlyMap<string, { active: boolean }>>();
7
+
8
+ /** Event listeners start independent operations, not children of the writer. */
9
+ export function outsideTaskTransaction<T>(work: () => T): T {
10
+ return held.run(new Map(), work);
11
+ }
12
+
13
+ /** Cross-process, reentrant task transaction. Never hold this during model execution. */
14
+ export async function taskTransaction<T>(
15
+ root: string,
16
+ id: string,
17
+ work: () => Promise<T>,
18
+ ): Promise<T> {
19
+ const key = join(
20
+ root,
21
+ 'transactions',
22
+ createHash('sha256').update(id).digest('hex'),
23
+ );
24
+ if (held.getStore()?.get(key)?.active) return work();
25
+ return withStoreLock(key, async () => {
26
+ const token = { active: true };
27
+ try {
28
+ return await held.run(
29
+ new Map([...(held.getStore() ?? []), [key, token]]),
30
+ work,
31
+ );
32
+ } finally {
33
+ token.active = false;
34
+ }
35
+ });
36
+ }
@@ -2,7 +2,11 @@ export type CronTaskStatus = 'active' | 'paused' | 'completed';
2
2
  export type CronTaskKind = 'recurring' | 'once';
3
3
  export type CronSessionMode = 'persistent' | 'fresh';
4
4
  export type CronBindingStatus = 'bound' | 'needs_binding';
5
- export type CronAttentionReason = 'failure' | 'offline' | 'overlap' | 'workspace_unavailable';
5
+ export type CronAttentionReason =
6
+ | 'failure'
7
+ | 'offline'
8
+ | 'overlap'
9
+ | 'workspace_unavailable';
6
10
 
7
11
  interface CronScheduleState {
8
12
  human: string;
@@ -28,6 +32,8 @@ export type CronSchedule =
28
32
  export interface CronTask {
29
33
  version?: 2;
30
34
  revision?: number;
35
+ /** Execution configuration identity; statistics never change it. */
36
+ planId?: string;
31
37
  catchUp?: 'skip' | 'latest';
32
38
  notifications?: 'all' | 'failures';
33
39
  id: string;
@@ -41,7 +47,9 @@ export interface CronTask {
41
47
  * 不设 = 不限次数(配合 expiresAt/permanent 控制终止)。 */
42
48
  maxRuns?: number;
43
49
  schedule: CronSchedule;
44
- action: { type: 'prompt'; prompt: string } | { type: 'workflow'; command: string };
50
+ action:
51
+ | { type: 'prompt'; prompt: string }
52
+ | { type: 'workflow'; command: string };
45
53
  runtime: {
46
54
  cwd: string;
47
55
  environment: 'project';
@@ -79,7 +87,12 @@ export interface CronTaskDraft {
79
87
  schedule:
80
88
  | { type: 'once'; at: string; jitterMs?: number }
81
89
  | { type: 'cron'; cron: string; timezone: string; jitterMs?: number }
82
- | { type: 'interval'; intervalMs: number; anchorAt?: string; jitterMs?: number };
90
+ | {
91
+ type: 'interval';
92
+ intervalMs: number;
93
+ anchorAt?: string;
94
+ jitterMs?: number;
95
+ };
83
96
  action: CronTask['action'];
84
97
  runtime: {
85
98
  cwd: string;
@@ -92,13 +105,26 @@ export interface CronTaskDraft {
92
105
  }
93
106
 
94
107
  export interface CronRunRecord {
108
+ planId?: string;
109
+ /** Full older output remains in this immutable local journal archive. */
110
+ archiveFile?: string;
111
+ /** Immutable execution configuration captured at enqueue time. */
112
+ snapshot?: CronTask;
113
+ completionStatus?: string;
114
+ managedStatus?: string;
95
115
  id: string;
96
116
  taskId: string;
97
117
  taskName: string;
98
118
  scheduledFor?: string;
99
119
  startedAt: string;
100
120
  finishedAt?: string;
101
- status: 'queued' | 'running' | 'success' | 'failure' | 'interrupted' | 'cancelled';
121
+ status:
122
+ | 'queued'
123
+ | 'running'
124
+ | 'success'
125
+ | 'failure'
126
+ | 'interrupted'
127
+ | 'cancelled';
102
128
  owner?: string;
103
129
  result?: string;
104
130
  cwd: string;
@@ -0,0 +1,419 @@
1
+ import { afterEach, beforeEach, expect, test } from 'bun:test';
2
+ import { mkdtemp, rm, readFile } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { Scheduler } from '../src/scheduler.js';
6
+ import {
7
+ createTask,
8
+ upsertTask,
9
+ getTask,
10
+ deleteTask,
11
+ recentRuns,
12
+ listTasks,
13
+ } from '../src/store.js';
14
+ import { requestRun, requestStop } from '../src/requests.js';
15
+ import { updateCronFromPatch } from '../src/service.js';
16
+ import { handleCronCommand } from '../src/commands.js';
17
+ import { executionOutcome } from '../../../src/session/executionOutcome.js';
18
+ import { scheduleTool } from '../../../src/tools/schedule/schedule.js';
19
+ import {
20
+ startBackgroundTask,
21
+ type BackgroundTask,
22
+ } from '../../../src/tools/tasks/backgroundTaskService.js';
23
+ import { taskTransaction, outsideTaskTransaction } from '../src/transaction.js';
24
+ import {
25
+ compactRunLog,
26
+ appendRun as appendRunFile,
27
+ recentRuns as readRuns,
28
+ } from '../src/runs.js';
29
+ import type {
30
+ RunAgentTurnOptions,
31
+ RunAgentTurnResult,
32
+ } from '../../../src/session/runAgentTurn.js';
33
+
34
+ let root: string;
35
+ let oldRoot: string | undefined;
36
+ let oldHome: string | undefined;
37
+ const schedulers: Scheduler[] = [];
38
+ const provider = {
39
+ name: 'test',
40
+ baseURL: 'https://example.invalid',
41
+ apiKey: 'test',
42
+ model: 'test',
43
+ contextWindow: 128000,
44
+ };
45
+ const success = (): RunAgentTurnResult => ({
46
+ ok: true,
47
+ result: 'ok',
48
+ events: [{ type: 'turn_done', completionStatus: 'completed' }],
49
+ numTurns: 1,
50
+ });
51
+ const task = () =>
52
+ createTask({
53
+ name: 'audit',
54
+ intervalMs: 60000,
55
+ timezone: 'UTC',
56
+ cwd: root,
57
+ sessionMode: 'fresh',
58
+ action: { type: 'prompt', prompt: 'old prompt' },
59
+ });
60
+ function scheduler(
61
+ run: (o: RunAgentTurnOptions) => Promise<RunAgentTurnResult>,
62
+ limits?: { concurrency: number; timeoutMs: number },
63
+ ) {
64
+ const s = new Scheduler({ provider, runAgentTurn: run }, limits);
65
+ schedulers.push(s);
66
+ return s;
67
+ }
68
+ beforeEach(async () => {
69
+ oldRoot = process.env.MINIMAL_AGENT_CRON_RUNNER_HOME;
70
+ oldHome = process.env.MINIMAL_AGENT_HOME;
71
+ root = await mkdtemp(join(tmpdir(), 'cron-lifecycle-'));
72
+ process.env.MINIMAL_AGENT_CRON_RUNNER_HOME = root;
73
+ process.env.MINIMAL_AGENT_HOME = root;
74
+ });
75
+ afterEach(async () => {
76
+ for (const s of schedulers.splice(0)) await s.stop();
77
+ await rm(root, { recursive: true, force: true });
78
+ if (oldRoot === undefined) delete process.env.MINIMAL_AGENT_CRON_RUNNER_HOME;
79
+ else process.env.MINIMAL_AGENT_CRON_RUNNER_HOME = oldRoot;
80
+ if (oldHome === undefined) delete process.env.MINIMAL_AGENT_HOME;
81
+ else process.env.MINIMAL_AGENT_HOME = oldHome;
82
+ });
83
+
84
+ test('deletion between task listing and enqueue cannot execute the deleted task', async () => {
85
+ const t = task();
86
+ t.createdAt = new Date(Date.now() - 120000).toISOString();
87
+ if (t.schedule.type === 'interval') t.schedule.anchorAt = t.createdAt;
88
+ t.catchUp = 'latest';
89
+ await upsertTask(t);
90
+ let invoked = false;
91
+ const s = scheduler(async () => {
92
+ invoked = true;
93
+ return success();
94
+ });
95
+ const engine = s as any;
96
+ const processDue = engine.processDueTask.bind(s);
97
+ engine.processDueTask = async (snapshot: typeof t, now: number) => {
98
+ await requestStop(t.id);
99
+ await deleteTask(t.id);
100
+ await processDue(snapshot, now);
101
+ };
102
+ await engine.reconcile();
103
+ await Promise.all(engine.executions.values());
104
+ expect(invoked).toBe(false);
105
+ expect(await getTask(t.id)).toBeUndefined();
106
+ });
107
+
108
+ test('deletion after enqueue prevents claim and keeps a cancelled receipt', async () => {
109
+ const t = await upsertTask(task());
110
+ await requestRun(t.id);
111
+ await deleteTask(t.id);
112
+ let invoked = false;
113
+ const s = scheduler(async () => {
114
+ invoked = true;
115
+ return success();
116
+ });
117
+ await (s as any).reconcile();
118
+ expect(invoked).toBe(false);
119
+ expect((await recentRuns(t.id))[0]?.status).toBe('cancelled');
120
+ });
121
+
122
+ test('queued executions use a complete immutable snapshot after editing', async () => {
123
+ const t = await upsertTask(task());
124
+ await requestRun(t.id);
125
+ await updateCronFromPatch({
126
+ id: t.id,
127
+ action: { type: 'prompt', prompt: 'new prompt' },
128
+ runtime: { cwd: join(root, 'different'), model: 'new-model' },
129
+ });
130
+ let seen: RunAgentTurnOptions | undefined;
131
+ const s = scheduler(async (o) => {
132
+ seen = o;
133
+ return success();
134
+ });
135
+ await s.runTaskNow(t.id);
136
+ expect(seen?.input).toBe('old prompt');
137
+ expect(seen?.cwd).toBe(root);
138
+ expect(seen?.model).toBeUndefined();
139
+ });
140
+
141
+ test('an old one-shot result cannot complete a rescheduled plan', async () => {
142
+ const t = task();
143
+ t.kind = 'once';
144
+ t.schedule = {
145
+ type: 'once',
146
+ at: new Date(Date.now() + 60000).toISOString(),
147
+ human: '',
148
+ };
149
+ await upsertTask(t);
150
+ let started!: () => void;
151
+ const ready = new Promise<void>((r) => (started = r));
152
+ let finish!: () => void;
153
+ const wait = new Promise<void>((r) => (finish = r));
154
+ const s = scheduler(async () => {
155
+ started();
156
+ await wait;
157
+ return success();
158
+ });
159
+ const work = s.runTaskNow(t.id);
160
+ await ready;
161
+ try {
162
+ await updateCronFromPatch({
163
+ id: t.id,
164
+ schedule: {
165
+ type: 'once',
166
+ at: new Date(Date.now() + 120000).toISOString(),
167
+ },
168
+ });
169
+ } finally {
170
+ finish();
171
+ }
172
+ await work;
173
+ expect((await getTask(t.id))?.status).toBe('active');
174
+ expect((await getTask(t.id))?.stats.runCount).toBe(1);
175
+ });
176
+
177
+ test.each([
178
+ 'delivery_incomplete',
179
+ 'delivery_unverified',
180
+ 'claims_unverified',
181
+ 'no_answer',
182
+ ])(
183
+ 'non-final delivery %s never becomes cron success',
184
+ async (completionStatus) => {
185
+ const t = await upsertTask(task());
186
+ const s = scheduler(async () => ({
187
+ ...success(),
188
+ events: [{ type: 'turn_done', completionStatus }],
189
+ }));
190
+ await s.runTaskNow(t.id);
191
+ expect((await recentRuns(t.id))[0]).toMatchObject({
192
+ status: 'failure',
193
+ completionStatus,
194
+ });
195
+ },
196
+ );
197
+
198
+ test('background work, blocked and acceptance-pending receipts remain explicit', () => {
199
+ expect(executionOutcome([]).error).toContain('缺少回合完成回执');
200
+ for (const done of [
201
+ { pendingBackground: [{}] },
202
+ { pendingRequired: [{}] },
203
+ { managedStatus: 'blocked' },
204
+ { managedStatus: 'ready_for_acceptance' },
205
+ ])
206
+ expect(
207
+ executionOutcome([{ type: 'turn_done', ...done }]).error,
208
+ ).toBeTruthy();
209
+ });
210
+
211
+ test('execution timeout cancels the runtime and records failure, not success', async () => {
212
+ const t = await upsertTask(task());
213
+ const s = scheduler(
214
+ async (o) => {
215
+ await new Promise<void>((r) => {
216
+ if (o.signal?.aborted) r();
217
+ else o.signal?.addEventListener('abort', () => r(), { once: true });
218
+ });
219
+ return success();
220
+ },
221
+ { concurrency: 1, timeoutMs: 20 },
222
+ );
223
+ await s.runTaskNow(t.id);
224
+ expect((await recentRuns(t.id))[0]).toMatchObject({
225
+ status: 'failure',
226
+ error: '计划执行超时',
227
+ });
228
+ });
229
+
230
+ test('global concurrency bounds distinct queued schedules', async () => {
231
+ const tasks = await Promise.all([
232
+ upsertTask(task()),
233
+ upsertTask(task()),
234
+ upsertTask(task()),
235
+ ]);
236
+ for (const t of tasks) await requestRun(t.id);
237
+ let active = 0;
238
+ let maximum = 0;
239
+ const s = scheduler(
240
+ async (o) => {
241
+ active++;
242
+ maximum = Math.max(maximum, active);
243
+ await new Promise<void>((r) => {
244
+ if (o.signal?.aborted) r();
245
+ else o.signal?.addEventListener('abort', () => r(), { once: true });
246
+ });
247
+ active--;
248
+ return success();
249
+ },
250
+ { concurrency: 2, timeoutMs: 1000 },
251
+ );
252
+ await (s as any).reconcile();
253
+ for (let i = 0; active < 2 && i < 100; i++) await Bun.sleep(5);
254
+ expect(active).toBe(2);
255
+ expect(maximum).toBe(2);
256
+ });
257
+
258
+ test('commands require real host identity and preserve Windows paths', async () => {
259
+ expect(await handleCronCommand('cron', '120m hello', null)).toContain(
260
+ '缺少当前会话',
261
+ );
262
+ expect(await listTasks()).toHaveLength(0);
263
+ await handleCronCommand(
264
+ 'cron',
265
+ 'create --name audit --interval 2h --prompt "Read C:\\code\\file.txt"',
266
+ null,
267
+ { cwd: root, sessionId: 'actual-session' },
268
+ );
269
+ expect((await listTasks())[0]?.runtime.sessionId).toBe('actual-session');
270
+ expect((await listTasks())[0]?.action).toEqual({
271
+ type: 'prompt',
272
+ prompt: 'Read C:\\code\\file.txt',
273
+ });
274
+ });
275
+
276
+ test('invalid patches do not write and Schedule denies background callers', async () => {
277
+ const t = await upsertTask(task());
278
+ const before = await getTask(t.id);
279
+ await expect(
280
+ updateCronFromPatch({ id: t.id, expiresAt: 'invalid' }),
281
+ ).rejects.toThrow();
282
+ expect(await getTask(t.id)).toEqual(before);
283
+ const r = await scheduleTool.callWithContext!(
284
+ { action: 'delete', id: t.id },
285
+ undefined,
286
+ {
287
+ cwd: root,
288
+ sessionId: 's',
289
+ surface: 'headless',
290
+ memoryAccess: 'local-owner',
291
+ },
292
+ );
293
+ expect(r.ok).toBe(false);
294
+ expect(await getTask(t.id)).toBeTruthy();
295
+ });
296
+
297
+ test('Schedule creates idempotently, scopes listing and deletes through the shared service', async () => {
298
+ const ctx = {
299
+ cwd: root,
300
+ sessionId: 's',
301
+ surface: 'tui' as const,
302
+ owner: 'local-owner' as const,
303
+ memoryAccess: 'denied' as const,
304
+ };
305
+ const input = {
306
+ action: 'create' as const,
307
+ requestId: 'stable',
308
+ name: 'test',
309
+ schedule: { type: 'interval' as const, intervalMs: 60000 },
310
+ execution: { type: 'prompt' as const, prompt: 'hello' },
311
+ sessionMode: 'fresh' as const,
312
+ };
313
+ for (let i = 0; i < 2; i++)
314
+ expect(
315
+ (await scheduleTool.callWithContext!(input, undefined, ctx)).ok,
316
+ ).toBe(true);
317
+ const tasks = await listTasks();
318
+ expect(tasks).toHaveLength(1);
319
+ const denied = await scheduleTool.callWithContext!(
320
+ { action: 'delete', id: tasks[0]!.id },
321
+ undefined,
322
+ { ...ctx, cwd: join(root, 'other') },
323
+ );
324
+ expect(denied.ok).toBe(false);
325
+ expect(
326
+ (
327
+ await scheduleTool.callWithContext!(
328
+ { action: 'delete', id: tasks[0]!.id },
329
+ undefined,
330
+ ctx,
331
+ )
332
+ ).ok,
333
+ ).toBe(true);
334
+ expect(await listTasks()).toHaveLength(0);
335
+ });
336
+
337
+ test('archiving retains full raw history, IDs, plan identity and active snapshots', async () => {
338
+ const t = task();
339
+ const dir = join(root, 'logs');
340
+ for (let i = 0; i < 103; i++)
341
+ await appendRunFile(dir, {
342
+ id: `r${i}`,
343
+ taskId: t.id,
344
+ taskName: t.name,
345
+ startedAt: new Date(1000 + i).toISOString(),
346
+ status: i === 102 ? 'queued' : 'success',
347
+ snapshot: t,
348
+ result: `full result ${i}`,
349
+ cwd: root,
350
+ sessionId: 's',
351
+ });
352
+ await compactRunLog(dir, t.id);
353
+ const all = await readRuns(dir, t.id, Infinity);
354
+ expect(all).toHaveLength(103);
355
+ expect(all[0]?.snapshot?.planId).toBe(t.planId);
356
+ const archived = all.find((r) => r.id === 'r0')!;
357
+ expect(archived.result).toBeUndefined();
358
+ expect(archived.planId).toBe(t.planId);
359
+ expect(await readFile(archived.archiveFile!, 'utf8')).toContain(
360
+ 'full result 0',
361
+ );
362
+ expect(await readRuns(dir, t.id, Infinity, true)).toHaveLength(1);
363
+ });
364
+
365
+ test('notifications cannot inherit a writer transaction and bypass its lock', async () => {
366
+ const order: string[] = [];
367
+ let listener!: Promise<void>;
368
+ await taskTransaction(root, 'same', async () => {
369
+ listener = outsideTaskTransaction(() =>
370
+ taskTransaction(root, 'same', async () => {
371
+ order.push('listener');
372
+ }),
373
+ );
374
+ await Bun.sleep(30);
375
+ expect(order).toEqual([]);
376
+ order.push('writer');
377
+ });
378
+ await listener;
379
+ expect(order).toEqual(['writer', 'listener']);
380
+ });
381
+
382
+ test('changing schedule type and clearing limits rotate the execution identity', async () => {
383
+ const t = task();
384
+ t.runtime.maxTurns = 10;
385
+ t.kind = 'once';
386
+ await upsertTask(t);
387
+ const cleared = await updateCronFromPatch({ id: t.id, clearMaxTurns: true });
388
+ expect(cleared.planId).not.toBe(t.planId);
389
+ const recurring = await updateCronFromPatch({
390
+ id: t.id,
391
+ schedule: { type: 'interval', intervalMs: 120000 },
392
+ });
393
+ expect(recurring.kind).toBe('recurring');
394
+ });
395
+
396
+ test('a real unfinished process is reported and stopped without leaking to later cron runs', async () => {
397
+ const t = await upsertTask(task());
398
+ let child: BackgroundTask | undefined;
399
+ const s = scheduler(async (options) => {
400
+ child = await startBackgroundTask(
401
+ {
402
+ command: 'isolated cron test',
403
+ cwd: root,
404
+ env: process.env,
405
+ executable: process.execPath,
406
+ args: ['-e', 'setInterval(() => {}, 1000)'],
407
+ sessionId: options.sessionId,
408
+ },
409
+ options.sessionState!.backgroundTasks,
410
+ );
411
+ return success();
412
+ });
413
+ await s.runTaskNow(t.id);
414
+ expect((await recentRuns(t.id))[0]).toMatchObject({
415
+ status: 'failure',
416
+ completionStatus: 'delivery_incomplete',
417
+ });
418
+ expect(child?.status).toBe('stopped');
419
+ });
@@ -36,8 +36,9 @@ describe('cron-runner plugin integration', () => {
36
36
  const history: Message[] = [{ role: 'system', content: 'test' }];
37
37
  let text = '';
38
38
  for await (const ev of runWithPlugins(
39
- '/cron create --name "Daily" --cron "7 6 * * *" --prompt "hello"',
40
- { provider, history },
39
+ '/cron create --name "Daily" --cron "7 6 * * *" --prompt "hello" --fresh-session',
40
+ { provider, history, runtimeContext: { surface: 'tui', profile: 'main', owner: 'local-owner',
41
+ cwd: root, sessionId: 'integration-session', memoryAccess: 'denied', interactiveAsk: true } },
41
42
  )) {
42
43
  if (ev.type === 'text') text += ev.delta;
43
44
  }
@@ -167,7 +167,7 @@ test('standby takes over and durable queued requests run only once', async () =>
167
167
  provider,
168
168
  runAgentTurn: async () => {
169
169
  calls++;
170
- return { ok: true, result: 'done', numTurns: 1, events: [] };
170
+ return { ok: true, result: 'done', numTurns: 1, events: [{ type: 'turn_done', completionStatus: 'completed' }] };
171
171
  },
172
172
  };
173
173
  const first = new Scheduler(ctx);
@@ -222,7 +222,7 @@ test('crash recovery marks started attempts unknown and resumes only queued atte
222
222
  provider,
223
223
  runAgentTurn: async () => {
224
224
  calls++;
225
- return { ok: true, result: 'ok', numTurns: 1, events: [] };
225
+ return { ok: true, result: 'ok', numTurns: 1, events: [{ type: 'turn_done', completionStatus: 'completed' }] };
226
226
  },
227
227
  });
228
228
  schedulers.push(s);
@@ -28,7 +28,9 @@ describe('cron-runner store and scheduler', () => {
28
28
  process.env.MINIMAL_AGENT_CRON_RUNNER_HOME = root;
29
29
  process.env.MINIMAL_AGENT_CRON_DISABLE_JITTER = '1';
30
30
  store = await import('../src/store.js');
31
- commands = await import('../src/commands.js');
31
+ const commandModule = await import('../src/commands.js');
32
+ commands = { ...commandModule, handleCronCommand: (name, args, scheduler, context) =>
33
+ commandModule.handleCronCommand(name, args, scheduler, context ?? { cwd: root, sessionId: 'test-session' }) };
32
34
  schedulerMod = await import('../src/scheduler.js');
33
35
  lockMod = await import('../src/lock.js');
34
36
  });
@@ -153,7 +155,7 @@ describe('cron-runner store and scheduler', () => {
153
155
  ok: true,
154
156
  result: 'done',
155
157
  numTurns: 1,
156
- events: [],
158
+ events: [{ type: 'turn_done', completionStatus: 'completed' }],
157
159
  }),
158
160
  };
159
161
  const scheduler = new schedulerMod.Scheduler(ctx);
@@ -244,7 +246,7 @@ describe('cron-runner store and scheduler', () => {
244
246
  const ctx: PluginRuntimeContext = {
245
247
  provider,
246
248
  runAgentTurn: async (): Promise<RunAgentTurnResult> => ({
247
- ok: true, result: 'ok', numTurns: 1, events: [],
249
+ ok: true, result: 'ok', numTurns: 1, events: [{ type: 'turn_done', completionStatus: 'completed' }],
248
250
  }),
249
251
  };
250
252
  const first = new schedulerMod.Scheduler(ctx);
@@ -328,7 +330,7 @@ describe('cron-runner store and scheduler', () => {
328
330
  await store.upsertTask(task);
329
331
  const ctx: PluginRuntimeContext = {
330
332
  provider,
331
- runAgentTurn: async (): Promise<RunAgentTurnResult> => ({ ok: true, result: 'ok', numTurns: 1, events: [] }),
333
+ runAgentTurn: async (): Promise<RunAgentTurnResult> => ({ ok: true, result: 'ok', numTurns: 1, events: [{ type: 'turn_done', completionStatus: 'completed' }] }),
332
334
  };
333
335
  const scheduler = new schedulerMod.Scheduler(ctx);
334
336
  await scheduler.runTaskNow(task.id);
@@ -358,7 +360,7 @@ describe('cron-runner store and scheduler', () => {
358
360
  provider,
359
361
  runAgentTurn: async (): Promise<RunAgentTurnResult> => {
360
362
  calls++;
361
- return { ok: true, result: 'ok', numTurns: 1, events: [] };
363
+ return { ok: true, result: 'ok', numTurns: 1, events: [{ type: 'turn_done', completionStatus: 'completed' }] };
362
364
  },
363
365
  });
364
366
  const internal = scheduler as unknown as {
@@ -384,7 +386,7 @@ describe('cron-runner store and scheduler', () => {
384
386
  provider,
385
387
  runAgentTurn: async (opts): Promise<RunAgentTurnResult> => {
386
388
  seen.push(opts.sessionId);
387
- return { ok: true, result: 'ok', numTurns: 1, events: [] };
389
+ return { ok: true, result: 'ok', numTurns: 1, events: [{ type: 'turn_done', completionStatus: 'completed' }] };
388
390
  },
389
391
  };
390
392
  const firstSessionId = 'persistent-session-a';
@@ -437,7 +439,7 @@ describe('cron-runner store and scheduler', () => {
437
439
  provider,
438
440
  runAgentTurn: async (): Promise<RunAgentTurnResult> => {
439
441
  calls++;
440
- return { ok: true, result: 'ok', numTurns: 1, events: [] };
442
+ return { ok: true, result: 'ok', numTurns: 1, events: [{ type: 'turn_done', completionStatus: 'completed' }] };
441
443
  },
442
444
  };
443
445
  const scheduler = new schedulerMod.Scheduler(ctx);
@@ -68,6 +68,7 @@ const api = {
68
68
  },
69
69
  }).catch(() => undefined));
70
70
  yield* runWorkflowFromCommand(args, {
71
+ presentArtifacts: ctx.presentArtifacts,
71
72
  provider: ctx.provider,
72
73
  history: ctx.history,
73
74
  signal: ctx.signal,
@@ -82,6 +82,7 @@ const api: PluginApi = {
82
82
  }).catch(() => undefined));
83
83
 
84
84
  yield* runWorkflowFromCommand(args, {
85
+ presentArtifacts: ctx.presentArtifacts,
85
86
  provider: ctx.provider,
86
87
  history: ctx.history,
87
88
  signal: ctx.signal,
@@ -210,6 +210,7 @@ export async function* runWorkflowFromCommand(rawArgs, opts) {
210
210
  }
211
211
  await refreshStableSystemPrompt(opts.history, cwd, tools);
212
212
  const ctx = {
213
+ presentArtifacts: opts.presentArtifacts,
213
214
  executionId: opts.executionId,
214
215
  provider: opts.provider,
215
216
  runtimeContext: opts.runtimeContext,
@@ -34,6 +34,7 @@ import { abandonWorkflowTask } from './workflowState.js';
34
34
  import type { InputDef, RunContext } from './types.js';
35
35
 
36
36
  export interface RunWorkflowFromCommandOptions {
37
+ presentArtifacts?: PluginContext['presentArtifacts'];
37
38
  provider: Provider;
38
39
  runtimeContext?: AgentRuntimeContext;
39
40
  history: Message[];
@@ -274,6 +275,7 @@ export async function* runWorkflowFromCommand(
274
275
 
275
276
  await refreshStableSystemPrompt(opts.history, cwd, tools);
276
277
  const ctx: RunContext = {
278
+ presentArtifacts: opts.presentArtifacts,
277
279
  executionId: opts.executionId,
278
280
  provider: opts.provider,
279
281
  runtimeContext: opts.runtimeContext,
@@ -138,8 +138,11 @@ async function* executeWorkflowScript(script, opts) {
138
138
  ...(!opts.parentStateDir ? { commandResult: true } : {}),
139
139
  delta: `工作流「${script.name}」的这个目标此前已完成,产物:\n${list}\n换个目标即可重新执行。\n`,
140
140
  };
141
- if (!opts.parentStateDir)
141
+ if (!opts.parentStateDir) {
142
+ if (ctx.presentArtifacts && !ctx.managedBridge)
143
+ yield* ctx.presentArtifacts((resume.artifacts ?? []).map(p => resolve(state.workingDir, p)));
142
144
  yield { type: 'turn_done' };
145
+ }
143
146
  return {
144
147
  workflow: script.name,
145
148
  runId: opts.runId,
@@ -470,6 +473,8 @@ async function* executeWorkflowScript(script, opts) {
470
473
  // ⚠️ 收尾状态必须过进程边界。传进去 'verified' 拿回来的很可能是
471
474
  // 'ready_for_acceptance' —— 机器自检通过但还没人验收,这两者对宿主是天差地别。
472
475
  // 就地丢弃会让 `-p --output-format json` 的宿主把「等待验收」读成「办完了」。
476
+ if (ctx.presentArtifacts && !ctx.managedBridge)
477
+ yield* ctx.presentArtifacts(artifacts);
473
478
  yield { type: 'turn_done', ...managedStatusOf(finished) };
474
479
  return {
475
480
  workflow: script.name,