@yu_robotics/remote-cli 1.6.255 → 1.6.261

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 (136) hide show
  1. package/dist/client/MessageHandler.d.ts +5 -12
  2. package/dist/client/MessageHandler.d.ts.map +1 -1
  3. package/dist/client/MessageHandler.js +53 -252
  4. package/dist/client/MessageHandler.js.map +1 -1
  5. package/dist/commands/start.d.ts.map +1 -1
  6. package/dist/commands/start.js +0 -3
  7. package/dist/commands/start.js.map +1 -1
  8. package/dist/delegation/DelegatedWorkerLaneCleanup.d.ts.map +1 -1
  9. package/dist/delegation/DelegatedWorkerLaneCleanup.js +10 -1
  10. package/dist/delegation/DelegatedWorkerLaneCleanup.js.map +1 -1
  11. package/dist/delegation/DelegationManager.d.ts +1 -1
  12. package/dist/delegation/DelegationManager.js +2 -2
  13. package/dist/delegation/DelegationManager.js.map +1 -1
  14. package/dist/executor/AcpExecutor.d.ts.map +1 -1
  15. package/dist/executor/AcpExecutor.js.map +1 -1
  16. package/dist/executor/AgyExecutor.d.ts +48 -168
  17. package/dist/executor/AgyExecutor.d.ts.map +1 -1
  18. package/dist/executor/AgyExecutor.js +377 -1082
  19. package/dist/executor/AgyExecutor.js.map +1 -1
  20. package/dist/executor/ClaudePersistentExecutor.d.ts +3 -7
  21. package/dist/executor/ClaudePersistentExecutor.d.ts.map +1 -1
  22. package/dist/executor/ClaudePersistentExecutor.js +14 -224
  23. package/dist/executor/ClaudePersistentExecutor.js.map +1 -1
  24. package/dist/executor/DshExecutor.d.ts +7 -14
  25. package/dist/executor/DshExecutor.d.ts.map +1 -1
  26. package/dist/executor/DshExecutor.js +48 -50
  27. package/dist/executor/DshExecutor.js.map +1 -1
  28. package/dist/executor/IExecutor.d.ts +2 -2
  29. package/dist/executor/IExecutor.d.ts.map +1 -1
  30. package/dist/executor/acp/AcpClient.d.ts +15 -1
  31. package/dist/executor/acp/AcpClient.d.ts.map +1 -1
  32. package/dist/executor/acp/AcpClient.js +85 -7
  33. package/dist/executor/acp/AcpClient.js.map +1 -1
  34. package/dist/executor/agy/AgyAcpDiagnostics.d.ts +8 -0
  35. package/dist/executor/agy/AgyAcpDiagnostics.d.ts.map +1 -0
  36. package/dist/executor/agy/AgyAcpDiagnostics.js +47 -0
  37. package/dist/executor/agy/AgyAcpDiagnostics.js.map +1 -0
  38. package/dist/executor/agy/AgyAcpRuntime.d.ts +39 -24
  39. package/dist/executor/agy/AgyAcpRuntime.d.ts.map +1 -1
  40. package/dist/executor/agy/AgyAcpRuntime.js +234 -202
  41. package/dist/executor/agy/AgyAcpRuntime.js.map +1 -1
  42. package/dist/executor/agy/AgyChatHost.d.ts +34 -0
  43. package/dist/executor/agy/AgyChatHost.d.ts.map +1 -0
  44. package/dist/executor/agy/AgyChatHost.js +106 -0
  45. package/dist/executor/agy/AgyChatHost.js.map +1 -0
  46. package/dist/executor/agy/AgyPermissions.d.ts +13 -0
  47. package/dist/executor/agy/AgyPermissions.d.ts.map +1 -0
  48. package/dist/executor/agy/AgyPermissions.js +61 -0
  49. package/dist/executor/agy/AgyPermissions.js.map +1 -0
  50. package/dist/executor/agy/AgySessionSelection.d.ts +8 -0
  51. package/dist/executor/agy/AgySessionSelection.d.ts.map +1 -0
  52. package/dist/executor/agy/AgySessionSelection.js +86 -0
  53. package/dist/executor/agy/AgySessionSelection.js.map +1 -0
  54. package/dist/executor/agy/AgySessionSettings.d.ts +14 -0
  55. package/dist/executor/agy/AgySessionSettings.d.ts.map +1 -0
  56. package/dist/executor/agy/AgySessionSettings.js +73 -0
  57. package/dist/executor/agy/AgySessionSettings.js.map +1 -0
  58. package/dist/executor/dsh/DshAcpClient.d.ts +1 -1
  59. package/dist/executor/dsh/DshAcpClient.d.ts.map +1 -1
  60. package/dist/executor/dsh/DshAcpClient.js +3 -1
  61. package/dist/executor/dsh/DshAcpClient.js.map +1 -1
  62. package/dist/executor/index.d.ts +2 -1
  63. package/dist/executor/index.d.ts.map +1 -1
  64. package/dist/executor/index.js +3 -3
  65. package/dist/executor/index.js.map +1 -1
  66. package/dist/maintenance/release-notes.json +1 -1
  67. package/dist/scheduling/ScheduleCapabilities.d.ts +2 -2
  68. package/dist/scheduling/ScheduleCapabilities.js +4 -4
  69. package/dist/scheduling/ScheduleCapabilities.js.map +1 -1
  70. package/dist/scheduling/SchedulePurgeVerification.js +1 -1
  71. package/dist/scheduling/SchedulePurgeVerification.js.map +1 -1
  72. package/dist/scheduling/ScheduleService.d.ts +10 -29
  73. package/dist/scheduling/ScheduleService.d.ts.map +1 -1
  74. package/dist/scheduling/ScheduleService.js +160 -627
  75. package/dist/scheduling/ScheduleService.js.map +1 -1
  76. package/dist/scheduling/agy/AgyHookOwnership.d.ts +13 -0
  77. package/dist/scheduling/agy/AgyHookOwnership.d.ts.map +1 -0
  78. package/dist/scheduling/agy/AgyHookOwnership.js +449 -0
  79. package/dist/scheduling/agy/AgyHookOwnership.js.map +1 -0
  80. package/dist/scheduling/agy/AgyHookRelay.d.ts +3 -4
  81. package/dist/scheduling/agy/AgyHookRelay.d.ts.map +1 -1
  82. package/dist/scheduling/agy/AgyHookRelay.js +14 -98
  83. package/dist/scheduling/agy/AgyHookRelay.js.map +1 -1
  84. package/dist/scheduling/agy/AgySessionSchedules.d.ts +5 -5
  85. package/dist/scheduling/agy/AgySessionSchedules.d.ts.map +1 -1
  86. package/dist/scheduling/agy/AgySessionSchedules.js +20 -17
  87. package/dist/scheduling/agy/AgySessionSchedules.js.map +1 -1
  88. package/dist/scheduling/claude/ClaudeScheduleOwnership.d.ts +2 -6
  89. package/dist/scheduling/claude/ClaudeScheduleOwnership.d.ts.map +1 -1
  90. package/dist/scheduling/claude/ClaudeScheduleOwnership.js +12 -67
  91. package/dist/scheduling/claude/ClaudeScheduleOwnership.js.map +1 -1
  92. package/dist/scheduling/claude/ClaudeSessionSchedules.d.ts +4 -26
  93. package/dist/scheduling/claude/ClaudeSessionSchedules.d.ts.map +1 -1
  94. package/dist/scheduling/claude/ClaudeSessionSchedules.js +22 -145
  95. package/dist/scheduling/claude/ClaudeSessionSchedules.js.map +1 -1
  96. package/dist/scheduling/dsh/ScheduledSessionGuard.d.ts +12 -0
  97. package/dist/scheduling/dsh/ScheduledSessionGuard.d.ts.map +1 -0
  98. package/dist/scheduling/dsh/ScheduledSessionGuard.js +96 -0
  99. package/dist/scheduling/dsh/ScheduledSessionGuard.js.map +1 -0
  100. package/dist/scheduling/dsh/SessionScheduleBridge.d.ts.map +1 -1
  101. package/dist/scheduling/dsh/SessionScheduleBridge.js +0 -25
  102. package/dist/scheduling/dsh/SessionScheduleBridge.js.map +1 -1
  103. package/dist/scheduling/dsh/SessionScheduleClient.d.ts.map +1 -1
  104. package/dist/scheduling/dsh/SessionScheduleClient.js +0 -8
  105. package/dist/scheduling/dsh/SessionScheduleClient.js.map +1 -1
  106. package/dist/scheduling/dsh/sessionLaunch.js +1 -1
  107. package/dist/scheduling/dsh/sessionLaunch.js.map +1 -1
  108. package/dist/scheduling/types.d.ts +26 -77
  109. package/dist/scheduling/types.d.ts.map +1 -1
  110. package/dist/scheduling/types.js +1 -10
  111. package/dist/scheduling/types.js.map +1 -1
  112. package/dist/service/ServiceManager.js +1 -1
  113. package/dist/thread/ThreadExecutorPool.d.ts +4 -1
  114. package/dist/thread/ThreadExecutorPool.d.ts.map +1 -1
  115. package/dist/thread/ThreadExecutorPool.js +6 -3
  116. package/dist/thread/ThreadExecutorPool.js.map +1 -1
  117. package/dist/thread/ThreadManager.d.ts.map +1 -1
  118. package/dist/thread/ThreadManager.js +23 -2
  119. package/dist/thread/ThreadManager.js.map +1 -1
  120. package/native/prebuilds/darwin-arm64/managed_native.node +0 -0
  121. package/native/prebuilds/darwin-arm64/manifest.json +1 -1
  122. package/native/prebuilds/darwin-x64/managed_native.node +0 -0
  123. package/native/prebuilds/darwin-x64/manifest.json +1 -1
  124. package/native/prebuilds/win32-arm64/managed_native.node +0 -0
  125. package/native/prebuilds/win32-arm64/manifest.json +1 -1
  126. package/native/prebuilds/win32-x64/managed_native.node +0 -0
  127. package/native/prebuilds/win32-x64/manifest.json +1 -1
  128. package/package.json +1 -1
  129. package/dist/executor/agy/AgyDelegationConfig.d.ts +0 -3
  130. package/dist/executor/agy/AgyDelegationConfig.d.ts.map +0 -1
  131. package/dist/executor/agy/AgyDelegationConfig.js +0 -105
  132. package/dist/executor/agy/AgyDelegationConfig.js.map +0 -1
  133. package/dist/scheduling/agy/AgyCheckpoint.d.ts +0 -35
  134. package/dist/scheduling/agy/AgyCheckpoint.d.ts.map +0 -1
  135. package/dist/scheduling/agy/AgyCheckpoint.js +0 -160
  136. package/dist/scheduling/agy/AgyCheckpoint.js.map +0 -1
@@ -5,40 +5,47 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.AgyAcpRuntime = void 0;
7
7
  const promises_1 = __importDefault(require("fs/promises"));
8
- const AgyCheckpoint_1 = require("../../scheduling/agy/AgyCheckpoint");
8
+ const AgyChatHost_1 = require("./AgyChatHost");
9
+ const transcript_1 = require("../../scheduling/agy/transcript");
10
+ const AgyPermissions_1 = require("./AgyPermissions");
11
+ const Activity_1 = require("../Activity");
9
12
  const crypto_1 = require("crypto");
10
13
  const AcpClient_1 = require("../acp/AcpClient");
14
+ const AgySessionSettings_1 = require("./AgySessionSettings");
15
+ const AgyAcpDiagnostics_1 = require("./AgyAcpDiagnostics");
11
16
  const AgyScheduleHost_1 = require("../../scheduling/agy/AgyScheduleHost");
12
17
  const AgyHookRelay_1 = require("../../scheduling/agy/AgyHookRelay");
13
18
  const NativeBindings_1 = require("../../native/NativeBindings");
14
- /** Original ACP conversation. A one-use local checkpoint permits loading only
15
- * after exact group retirement before every possible owned native wake. */
19
+ /** ACP host for fresh main chat and qualified worker continuity. Loading never grants schedule admission. */
16
20
  class AgyAcpRuntime {
17
21
  options;
18
22
  client;
19
- handoff = false;
20
- handoffWork;
21
- continuing = false;
22
- continuationFailure;
23
- continued = false;
24
- get continuationSucceeded() { return this.continued; }
25
23
  entries = new Map();
26
- get continuationPending() { return this.continuing; }
27
- get checkpointClean() { return this.options.checkpoint?.read()?.state === 'clean'; }
28
24
  host;
25
+ chat;
26
+ settings;
27
+ defaults;
28
+ settingsBusy = false;
29
+ scheduleOperations = 0;
30
+ permissions = new AgyPermissions_1.AgyPermissions();
29
31
  relay;
30
32
  restore;
31
33
  starting;
32
34
  closing = false;
33
35
  closePromise;
34
- noJobs;
35
36
  activity;
36
37
  closed = false;
38
+ allocationStarted = false;
39
+ get allocationUnconfirmed() { return this.allocationStarted && !this.allocatedSessionId; }
40
+ relayFault = false;
41
+ continuityUnsafe = false;
42
+ allocatedSessionId;
37
43
  active;
38
- activeDone;
39
44
  retained = false;
40
45
  hostId = (0, crypto_1.randomUUID)();
41
46
  tools = new Map();
47
+ latestRecords = [];
48
+ tracker = new Activity_1.ActivityTracker();
42
49
  streamed = '';
43
50
  callbacks;
44
51
  constructor(options) {
@@ -52,23 +59,32 @@ class AgyAcpRuntime {
52
59
  this.streamed += block.text;
53
60
  this.active.onStream?.(block.text);
54
61
  this.active.onDisplayText?.(block.text);
62
+ this.tracker.emitPublicText(block.text);
55
63
  }
56
64
  },
57
- onPermissionRequest: async (_title, choices) => this.options.autoApprove
58
- ? choices.findIndex(choice => choice.kind === 'allow_once') : -1,
65
+ onPermissionRequest: (title, choices) => this.permissions.request(title, choices, this.active, this.options.autoApprove),
59
66
  };
60
67
  }
61
- get safeFallback() { return this.closed && !this.host; }
62
- get sessionId() { return this.host?.sessionId; }
68
+ get sessionId() { return this.host?.sessionId ?? this.chat?.sessionId; }
63
69
  get hasJobs() { return this.retained; }
64
- get busy() { return this.continuing || !this.closed && (!!this.active || !!this.starting || !!this.host?.schedules.busy); }
65
- get blocked() { return this.continuationFailure ?? this.host?.schedules.status.blocked; }
70
+ get busy() { return this.settingsBusy || this.scheduleOperations > 0 || !this.closed && (!!this.active || !!this.starting || !!this.host?.schedules.busy); }
71
+ get blocked() { return this.chat?.blocked ?? this.host?.schedules.status.blocked; }
72
+ get reusable() {
73
+ return !this.continuityUnsafe && !this.blocked && !this.retained && (this.chat?.reusable ?? true)
74
+ && !this.latestRecords.some(row => (0, transcript_1.nativeWake)(row) || row.type === 'GENERIC' && row.status !== 'DONE');
75
+ }
66
76
  get pendingMutation() { return !!this.host?.schedules.pendingMutation; }
77
+ get cleanupMutationPending() { return !!this.host?.schedules.cleanupMutationPending; }
78
+ /** Admission to retire our host, never proof that the host has already exited. */
79
+ get canRetireForContextReset() {
80
+ return !this.busy && !this.pendingMutation && (!this.retained || this.entries.size > 0
81
+ && [...this.entries.values()].every(entry => entry.cancelled && entry.handle.retirementConfirmed === true));
82
+ }
67
83
  get running() { return !!this.client && !this.closed; }
68
84
  async start() {
69
85
  if (this.closing || this.closed)
70
86
  throw new Error('AGY ACP host is retired.');
71
- if (this.host)
87
+ if (this.host || this.chat)
72
88
  return;
73
89
  if (this.starting)
74
90
  return this.starting;
@@ -77,7 +93,12 @@ class AgyAcpRuntime {
77
93
  await this.starting;
78
94
  }
79
95
  catch (error) {
80
- await this.close();
96
+ try {
97
+ await this.close();
98
+ }
99
+ catch (cleanup) {
100
+ throw new AgyAcpDiagnostics_1.AgyAcpStartupError('startup', error, cleanup);
101
+ }
81
102
  throw error;
82
103
  }
83
104
  finally {
@@ -85,99 +106,176 @@ class AgyAcpRuntime {
85
106
  }
86
107
  }
87
108
  async open() {
109
+ let stage = 'native-helper';
110
+ try {
111
+ await this.openSession(next => { stage = next; });
112
+ }
113
+ catch (error) {
114
+ throw new AgyAcpDiagnostics_1.AgyAcpStartupError(stage, error);
115
+ }
116
+ }
117
+ async openSession(setStage) {
88
118
  const native = (0, NativeBindings_1.nativeBindings)();
89
119
  if (!native.readChunk || !native.openOutputChild)
90
- throw new Error('AGY ACP transcript handle support is unavailable.');
120
+ throw new Error('AGY ACP native helper support is unavailable. Reinstall remote-cli on a published Linux, macOS or Windows x64/ARM64 target.');
121
+ setStage('hooks');
91
122
  await promises_1.default.mkdir(this.options.home, { recursive: true, mode: 0o700 });
92
123
  if (this.closing)
93
124
  throw new Error('AGY startup was retired.');
94
125
  this.relay = new AgyHookRelay_1.AgyHookRelay(this.options.home, (event, payload, rows) => {
95
- if (!this.host)
126
+ if (!this.host && !this.chat)
96
127
  throw new Error('AGY hook arrived before session admission.');
97
128
  this.activity?.();
98
- const decision = this.host.schedules.accept(event, payload, rows);
129
+ this.latestRecords = rows;
130
+ const decision = this.chat ? this.chat.accept(event, payload, rows) : this.host.schedules.accept(event, payload, rows);
131
+ if (!this.continuityUnsafe && (event === 'PreToolUse' && decision.decision === 'deny'
132
+ || rows.some(row => (0, transcript_1.creationReceipt)(row, payload.conversationId, row.step_index)))) {
133
+ this.continuityUnsafe = true;
134
+ this.options.settledPrompt?.(false);
135
+ }
99
136
  if (this.active && decision.decision !== 'deny') {
100
137
  if (event === 'PreToolUse') {
101
138
  const call = payload.toolCall;
102
139
  if (call && Number.isSafeInteger(payload.stepIdx)) {
103
140
  this.tools.set(payload.stepIdx, call.id);
104
- this.active.onToolUse?.({ id: call.id, ...this.options.mapTool(call.name, call.args) });
141
+ const mapped = this.options.mapTool(call.name, call.args);
142
+ const description = typeof call.args.toolSummary === 'string' ? call.args.toolSummary : undefined;
143
+ this.active.onToolUse?.({ id: call.id, ...mapped, ...(description ? { description } : {}) });
144
+ this.tracker.emitTool(mapped.name, mapped.input, description);
105
145
  }
106
146
  }
107
147
  for (const [step, id] of this.tools) {
108
148
  const row = rows.find(row => row.step_index === step && row.type === 'GENERIC' && row.status === 'DONE');
109
149
  if (row) {
110
- this.active.onToolResult?.({ tool_use_id: id, content: (row.content ?? '').slice(0, 32768), is_error: false });
150
+ this.active.onToolResult?.({ tool_use_id: id, content: (row.content ?? '').slice(0, 32768), is_error: event === 'PostToolUse' && !!payload.error });
111
151
  this.tools.delete(step);
112
152
  }
113
153
  }
114
154
  }
115
155
  return decision;
116
- }, () => this.host?.schedules.fence('AGY hook relay failed; native schedule state is unconfirmed.'));
156
+ }, () => { this.relayFault = true; this.chat?.fence('AGY hook relay failed; chat state is unconfirmed.'); this.host?.schedules.fence('AGY hook relay failed; native schedule state is unconfirmed.'); });
117
157
  this.restore = await (0, AgyHookRelay_1.installAgyScheduleHooks)(this.options.home, await this.relay.start());
118
158
  if (this.closing)
119
159
  throw new Error('AGY startup was retired.');
120
160
  const args = ['acp', '--stdio', '--process-per-session', '--disable-telemetry'];
121
161
  if (this.options.autoApprove)
122
162
  args.push('--dangerously-skip-permissions');
123
- if (this.options.model)
124
- args.push('--model', this.options.model);
125
- if (this.options.effort)
126
- args.push('--effort', this.options.effort);
127
- this.client = new AcpClient_1.AcpClient(this.options.command, args, this.options.cwd, this.callbacks, true, { env: this.options.env, delegationWorker: true, onStderr: () => { } });
163
+ setStage('process');
164
+ this.client = this.restore.run(() => new AcpClient_1.AcpClient(this.options.command, args, this.options.cwd, this.callbacks, true, { env: this.options.env, delegationWorker: true, onStderr: () => { } }));
165
+ setStage('initialize');
128
166
  await this.client.initialize();
129
167
  if (this.closing)
130
168
  throw new Error('AGY startup was retired.');
169
+ const setup = async (session, configure) => {
170
+ if (typeof session?.sessionId !== 'string' || !/^[a-zA-Z0-9_-]{1,128}$/.test(session.sessionId))
171
+ throw new Error('AGY ACP returned no valid session identity.');
172
+ this.allocatedSessionId = session.sessionId;
173
+ setStage('session-save');
174
+ try {
175
+ await this.options.saveSession(session.sessionId);
176
+ }
177
+ catch {
178
+ throw new Error('AGY ACP session identity could not be persisted. No prompt was sent.');
179
+ }
180
+ if (this.closing)
181
+ throw new Error('AGY startup was retired.');
182
+ setStage('session-settings');
183
+ this.defaults = { model: session.configOptions?.find(o => o.id === 'model')?.currentValue, effort: session.configOptions?.find(o => o.id === 'thought_level')?.currentValue };
184
+ this.settings = session;
185
+ await (0, AgySessionSettings_1.applyAgySessionSettings)(session, async (id, value) => {
186
+ if (this.closing)
187
+ throw new Error('AGY startup was retired.');
188
+ const result = await configure(id, value);
189
+ this.settings = result;
190
+ if (this.closing)
191
+ throw new Error('AGY startup was retired.');
192
+ return result;
193
+ }, this.options);
194
+ if (this.closing)
195
+ throw new Error('AGY startup was retired.');
196
+ };
131
197
  let session;
132
- if (this.options.resume) {
133
- this.client = await (0, AgyCheckpoint_1.loadCheckpointSession)(this.client, this.options.resume, this.options.cwd, this.options.mcpServers);
134
- session = { sessionId: this.options.resume.sessionId };
135
- this.options.resume = undefined;
198
+ // A lost/malformed allocation reply is not proof that no ACP session exists.
199
+ if (!this.options.sessionId)
200
+ this.options.beforeAllocation?.();
201
+ this.allocationStarted = true;
202
+ setStage(this.options.sessionId ? 'session-load' : 'session-create');
203
+ if (this.options.sessionId) {
204
+ if (!this.client.loadSessionWithSetup)
205
+ throw new Error('AGY ACP session load setup is unavailable.');
206
+ session = await this.client.loadSessionWithSetup(this.options.sessionId, this.options.cwd, this.options.mcpServers, setup);
207
+ if (session.sessionId !== this.options.sessionId)
208
+ throw new Error('AGY loaded a different session; no prompt was sent.');
209
+ }
210
+ else {
211
+ if (!this.client.newSessionWithSetup)
212
+ throw new Error('AGY ACP initial session setup is unavailable.');
213
+ session = await this.client.newSessionWithSetup(this.options.cwd, this.options.mcpServers, setup);
136
214
  }
137
- else
138
- session = await this.client.newSession(this.options.cwd, this.options.mcpServers);
139
215
  if (this.closing)
140
216
  throw new Error('AGY startup was retired.');
141
217
  if (!session.sessionId)
142
218
  throw new Error('AGY ACP returned no session identity.');
143
- this.options.saveSession(session.sessionId);
144
- this.host = new AgyScheduleHost_1.AgyScheduleHost(this.client, session.sessionId, {
145
- threadId: this.options.threadId, cwd: this.options.cwd,
146
- timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
147
- hostId: this.hostId, isCurrent: () => !this.closing,
148
- beforeMutation: async () => {
149
- this.options.retainScheduleOwner(session.sessionId, this.hostId, false);
150
- this.retained = true;
151
- },
152
- });
153
- this.host.bind(this.relay);
219
+ if (this.allocatedSessionId !== session.sessionId)
220
+ throw new Error('AGY ACP initial session setup was not confirmed.');
221
+ setStage('host-admission');
222
+ if (this.relayFault)
223
+ throw new Error('AGY hook relay failed before session admission.');
224
+ if (this.options.worker || this.options.sessionId) {
225
+ this.chat = new AgyChatHost_1.AgyChatHost(this.client, session.sessionId, this.options.cwd, this.options.threadId);
226
+ this.relay.bindSession(session.sessionId);
227
+ }
228
+ else {
229
+ this.host = new AgyScheduleHost_1.AgyScheduleHost(this.client, session.sessionId, {
230
+ threadId: this.options.threadId, cwd: this.options.cwd,
231
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
232
+ hostId: this.hostId, isCurrent: () => !this.closing,
233
+ beforeMutation: async () => {
234
+ this.options.retainScheduleOwner(session.sessionId, this.hostId, false);
235
+ this.retained = true;
236
+ },
237
+ });
238
+ this.host.bind(this.relay);
239
+ }
154
240
  void this.client.waitForExit().then(() => {
155
- if (!this.closing)
241
+ if (!this.closing) {
156
242
  this.host?.schedules.processClosed(false);
243
+ this.chat?.fence('AGY process closed unexpectedly.');
244
+ }
157
245
  });
158
246
  }
159
247
  async execute(prompt, options) {
160
248
  await this.start();
161
- if (this.active)
249
+ if (this.active || this.settingsBusy)
162
250
  throw new Error('AGY foreground turn is already active.');
163
251
  this.active = options;
164
252
  this.streamed = '';
165
253
  this.tools.clear();
254
+ this.tracker.setCallback(options.onActivity);
255
+ this.tracker.reset();
166
256
  let timer;
167
257
  let inactive;
168
258
  this.activity = () => {
169
259
  if (inactive)
170
260
  clearTimeout(inactive);
171
261
  if (options.inactivityTimeout && options.inactivityTimeout > 0)
172
- inactive = setTimeout(() => this.host.cancelForeground(), options.inactivityTimeout);
262
+ inactive = setTimeout(() => (this.chat ?? this.host).cancelForeground(), options.inactivityTimeout);
173
263
  };
174
264
  this.activity();
175
265
  try {
176
266
  if (options.timeout && options.timeout > 0)
177
- timer = setTimeout(() => this.host.cancelForeground(), options.timeout);
178
- const work = this.host.prompt([{ type: 'text', text: options.resolvePrompt?.(this.sessionId ?? null) ?? prompt }]);
179
- this.activeDone = work;
267
+ timer = setTimeout(() => (this.chat ?? this.host).cancelForeground(), options.timeout);
268
+ this.options.beforePrompt?.();
269
+ const blocks = [{ type: 'text', text: options.resolvePrompt?.(this.sessionId ?? null) ?? prompt },
270
+ ...(options.attachments ?? []).filter(item => item.type === 'image').map(item => ({ type: 'image', data: item.data, mimeType: item.mimeType }))];
271
+ const work = (this.chat ?? this.host).prompt(blocks);
180
272
  const result = await work;
273
+ if (result.stopReason === 'cancelled' && !this.retained && !this.relayFault && !this.chat
274
+ && this.host?.schedules.status.blocked?.startsWith('AGY foreground cancelled:')) {
275
+ this.chat = new AgyChatHost_1.AgyChatHost(this.client, this.sessionId, this.options.cwd, this.options.threadId, this.latestRecords);
276
+ this.host = undefined;
277
+ }
278
+ this.options.settledPrompt?.(this.reusable && result.stopReason !== 'cancelled');
181
279
  // Current native Stop gives the final text without replaying buffered ACP
182
280
  // output. With timers, this is a batch projection, not token streaming.
183
281
  if (result.output && (this.retained || !this.streamed)) {
@@ -185,170 +283,110 @@ class AgyAcpRuntime {
185
283
  options.onDisplayText?.(result.output);
186
284
  }
187
285
  return { success: result.success, output: result.output, sessionAbbr: this.sessionId?.slice(0, 8),
188
- ...(!result.success && { error: result.output }) };
286
+ ...(!result.success && { error: result.output || 'AGY native turn failed.' }) };
189
287
  }
190
288
  finally {
191
289
  if (timer)
192
290
  clearTimeout(timer);
193
291
  if (inactive)
194
292
  clearTimeout(inactive);
293
+ this.permissions.cancel();
294
+ this.tracker.reset();
295
+ this.tracker.setCallback(undefined);
195
296
  this.activity = undefined;
196
297
  this.active = undefined;
197
- this.activeDone = undefined;
198
298
  this.tools.clear();
199
299
  }
200
300
  }
201
301
  async abort() {
202
- this.continued = false;
203
- let window;
204
- let prepared;
205
- if (this.retained && this.options.checkpoint && this.active && !this.pendingMutation) {
206
- try {
207
- window = this.host.schedules.checkpointWindow(true);
208
- prepared = this.options.checkpoint.prepare(this.sessionId, this.definitions());
209
- this.handoff = true;
210
- this.continuing = true;
211
- }
212
- catch { /* Ordinary cancellation still works; unknown work remains fenced. */ }
213
- }
214
- const terminal = this.activeDone;
215
- const cancelled = this.host?.cancelForeground() ?? false;
216
- let confirmed = false;
217
- if (cancelled) {
218
- try {
219
- confirmed = (await terminal)?.stopReason === 'cancelled';
220
- }
221
- catch { /* No confirmed terminal: retain uncertainty. */ }
302
+ this.permissions.cancel();
303
+ return (this.chat ?? this.host)?.cancelForeground() ?? false;
304
+ }
305
+ async withOperation(id, current, run, inTurn) {
306
+ if (this.settingsBusy)
307
+ throw new Error('AGY settings are changing; native scheduling is unavailable.');
308
+ this.scheduleOperations++;
309
+ try {
310
+ await this.start();
311
+ if (!this.host)
312
+ throw new Error('Native scheduling is unavailable for loaded sessions and managed workers.');
313
+ return await this.host.schedules.withOperation(id, current, run, inTurn);
222
314
  }
223
- if (cancelled && window && prepared) {
224
- try {
225
- if (!confirmed)
226
- throw new Error('AGY foreground cancellation terminal is unconfirmed.');
227
- window();
228
- await this.close();
229
- window();
230
- this.options.checkpoint.confirm(prepared);
231
- await this.resumeCurrent();
232
- this.continued = true;
233
- }
234
- catch (error) {
235
- this.handoff = false;
236
- this.continuationFailure = error instanceof Error ? error.message : 'AGY continuation is unconfirmed.';
237
- this.host?.schedules.fence('AGY automatic continuation failed; retained work requires reconciliation.');
238
- for (const entry of this.entries.values())
239
- entry.emit({ type: 'stopped', exitConfirmed: false,
240
- reason: error instanceof Error ? error.message : 'AGY continuation is unconfirmed.' });
241
- }
242
- finally {
243
- this.continuing = false;
244
- }
315
+ finally {
316
+ this.scheduleOperations--;
245
317
  }
246
- return cancelled;
247
318
  }
248
- definitions() {
249
- return Object.fromEntries([...this.entries].filter(([, entry]) => !entry.cancelled)
250
- .map(([id, entry]) => [id, (0, AgyCheckpoint_1.scheduleDigest)(entry.input)]));
251
- }
252
- async resumeCurrent() {
253
- const entries = [...this.entries.values()].filter(entry => !entry.cancelled);
254
- if (entries.some(entry => !entry.current() || entry.input.rule.kind === 'once' && Date.parse(entry.input.rule.at) <= Date.now()))
255
- throw new Error('AGY continuation owner or deadline changed before loading.');
256
- const permit = this.options.checkpoint.consume(this.sessionId);
257
- this.client = undefined;
258
- this.host = undefined;
259
- this.relay = undefined;
260
- this.closed = false;
261
- this.closing = false;
262
- this.closePromise = undefined;
263
- this.starting = undefined;
264
- this.hostId = (0, crypto_1.randomUUID)();
265
- this.handoffWork = undefined;
266
- this.options.resume = permit;
267
- await this.start();
268
- await this.host.qualify();
269
- for (const entry of entries) {
270
- if (!entry.current() || entry.input.rule.kind === 'once' && Date.parse(entry.input.rule.at) <= Date.now())
271
- throw new Error('AGY continuation owner or deadline changed.');
272
- const previousNativeId = entry.handle.nativeId;
273
- entry.handle = await this.host.create(entry.input, event => { if (!this.handoff || event.type !== 'stopped')
274
- return entry.emit(event); }, entry.current);
275
- await entry.emit({ type: 'rebound', previousNativeId, nativeId: entry.handle.nativeId });
319
+ action(id) { return this.host?.schedules.action(id); }
320
+ async create(input, emit, current) {
321
+ if (this.settingsBusy)
322
+ throw new Error('AGY settings are changing; native scheduling is unavailable.');
323
+ this.scheduleOperations++;
324
+ try {
325
+ await this.start();
326
+ if (!this.host)
327
+ throw new Error('Native scheduling is unavailable for loaded sessions and managed workers.');
328
+ await this.host.qualify();
329
+ const entry = { input: structuredClone(input), emit, current, handle: undefined, cancelled: false };
330
+ const actual = await this.host.create(input, emit, current);
331
+ entry.handle = actual;
332
+ this.entries.set(input.id, entry);
333
+ return {
334
+ get nativeId() { return entry.handle.nativeId; },
335
+ get retirementConfirmed() { return entry.handle.retirementConfirmed; },
336
+ get nativeDefinitionAbsent() { return entry.handle.nativeDefinitionAbsent; },
337
+ cancellationKeepsRunning: true,
338
+ list: () => entry.handle.list(),
339
+ cancel: () => { entry.cancelled = true; return entry.handle.cancel(); },
340
+ stop: () => entry.handle.stop(),
341
+ };
342
+ }
343
+ finally {
344
+ this.scheduleOperations--;
276
345
  }
277
- this.handoff = false;
278
346
  }
279
- /** Shared ScheduleService calls this once per handle; the host-wide operation
280
- * is coalesced. Delete every owned definition before the first possible wake,
281
- * join the group before that same deadline, then publish a clean checkpoint. */
282
- releaseForRestart() {
283
- if (this.handoffWork)
284
- return this.handoffWork;
285
- if (!this.options.checkpoint || !this.host || this.active || this.pendingMutation)
286
- return Promise.reject(new Error('AGY handoff is busy or unavailable.'));
287
- let window;
347
+ isWaitingInput() { return this.permissions.waiting; }
348
+ sendInput(input) { return this.permissions.input(input); }
349
+ respondToApproval(id, action) { return this.permissions.respond(id, action); }
350
+ async waitForManagedProcessGroupExit() {
351
+ if (this.client && !this.client.waitForManagedProcessGroupExit)
352
+ throw new Error('AGY process group cannot be confirmed.');
353
+ await this.client?.waitForManagedProcessGroupExit?.();
354
+ }
355
+ async changeSettings(requested) {
356
+ if (this.busy || !this.reusable)
357
+ throw new Error('AGY settings require idle chat without retained native schedules or uncertain work.');
358
+ this.settingsBusy = true;
288
359
  try {
289
- window = this.host.schedules.checkpointWindow();
360
+ await this.start();
361
+ const selection = { mode: requested.mode, model: requested.resetModel ? this.defaults?.model : requested.model,
362
+ effort: requested.resetEffort ? this.defaults?.effort : requested.effort };
363
+ if (requested.resetModel && !selection.model || requested.resetEffort && !selection.effort)
364
+ throw new Error('AGY native setting default is unavailable.');
365
+ // Controls revoke the original scheduling token. No later setting recreates it.
366
+ if (!this.chat)
367
+ this.chat = new AgyChatHost_1.AgyChatHost(this.client, this.sessionId, this.options.cwd, this.options.threadId, this.latestRecords);
368
+ this.host = undefined;
369
+ await (0, AgySessionSettings_1.applyAgySessionSettings)(this.settings, async (id, value) => {
370
+ const result = await this.client.setConfigOption(this.sessionId, id, value);
371
+ this.settings = result;
372
+ return result;
373
+ }, selection);
290
374
  }
291
375
  catch (error) {
292
- return Promise.reject(error);
293
- } // No mutation: a later genuine idle retry is allowed.
294
- return this.handoffWork = (async () => {
295
- const prepared = this.options.checkpoint.prepare(this.sessionId, this.definitions());
296
- this.handoff = true;
297
- try {
298
- for (const entry of this.entries.values()) {
299
- window();
300
- await entry.handle.cancel();
301
- window();
302
- }
303
- await this.close();
304
- window();
305
- this.options.checkpoint.confirm(prepared);
306
- }
307
- catch (error) {
308
- this.handoff = false;
309
- this.host?.schedules.fence('AGY orderly handoff could not exclude queued work.');
310
- throw error;
311
- }
312
- })();
313
- }
314
- async withOperation(id, current, run, inTurn) {
315
- await this.start();
316
- return this.host.schedules.withOperation(id, current, run, inTurn);
317
- }
318
- action(id) { return this.host?.schedules.action(id); }
319
- async create(input, emit, current) {
320
- await this.start();
321
- await this.host.qualify();
322
- const entry = { input: structuredClone(input), emit, current, handle: undefined, cancelled: false };
323
- const actual = await this.host.create(input, event => { if (!this.handoff || event.type !== 'stopped')
324
- return emit(event); }, current);
325
- entry.handle = actual;
326
- this.entries.set(input.id, entry);
327
- return {
328
- get nativeId() { return entry.handle.nativeId; },
329
- recoveryIdentity: input.recovery?.identity,
330
- get retirementConfirmed() { return entry.handle.retirementConfirmed; },
331
- get nativeDefinitionAbsent() { return entry.handle.nativeDefinitionAbsent; },
332
- cancellationKeepsRunning: true,
333
- list: () => entry.handle.list(),
334
- cancel: () => { entry.cancelled = true; return entry.handle.cancel(); },
335
- stop: () => entry.handle.stop(),
336
- ...(this.options.checkpoint ? { releaseForRestart: async () => { await this.releaseForRestart(); return { nativeDefinitionAbsent: true }; } } : {}),
337
- };
376
+ this.chat?.fence('AGY setting outcome is unconfirmed; no further prompt was sent.');
377
+ throw error;
378
+ }
379
+ finally {
380
+ this.settingsBusy = false;
381
+ }
338
382
  }
339
383
  /** Join the exact tracked group before restoring hooks. Retirement does not
340
384
  * authorize loading this conversation: old SYSTEM reminders may survive. */
341
385
  close() {
342
386
  if (this.closed)
343
387
  return Promise.resolve();
344
- const noRemainingJobs = !this.retained || this.entries.size > 0 && [...this.entries.values()].every(entry => entry.cancelled && entry.handle.retirementConfirmed === true);
345
- if (!this.closing && noRemainingJobs && !this.active && this.host && this.options.checkpoint && !this.host.schedules.status.blocked) {
346
- try {
347
- this.noJobs = { check: this.host.schedules.checkpointWindow(), prepared: this.options.checkpoint.prepare(this.host.sessionId, {}) };
348
- }
349
- catch { /* Ordinary chat can still retire without granting ACP recovery. */ }
350
- }
351
388
  this.closing = true;
389
+ this.permissions.cancel();
352
390
  return this.closePromise ??= (async () => {
353
391
  await this.starting?.catch(() => { });
354
392
  await this.finishClose();
@@ -373,17 +411,11 @@ class AgyAcpRuntime {
373
411
  await this.relay?.close();
374
412
  await this.restore?.();
375
413
  this.restore = undefined;
376
- if (this.host)
377
- this.options.retireSession(this.host.sessionId);
414
+ if (!this.reusable)
415
+ this.options.settledPrompt?.(false);
416
+ if (this.host || this.chat)
417
+ this.options.ownedSessionClosed(this.sessionId);
378
418
  this.closed = true;
379
- if (this.noJobs) {
380
- try {
381
- this.noJobs.check();
382
- this.options.checkpoint.confirm(this.noJobs.prepared);
383
- }
384
- catch { /* No clean proof is published when quiescence expired. */ }
385
- this.noJobs = undefined;
386
- }
387
419
  }
388
420
  }
389
421
  exports.AgyAcpRuntime = AgyAcpRuntime;