@0xmaxma/claude-gateway 2.0.7 → 2.0.9
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/README.md +1 -0
- package/config.template.json +8 -3
- package/dist/agent/runner.d.ts +14 -0
- package/dist/agent/runner.d.ts.map +1 -1
- package/dist/agent/runner.js +83 -19
- package/dist/agent/runner.js.map +1 -1
- package/dist/api/router.d.ts.map +1 -1
- package/dist/api/router.js +116 -5
- package/dist/api/router.js.map +1 -1
- package/dist/api/voice-settings-router.d.ts.map +1 -1
- package/dist/api/voice-settings-router.js +2 -1
- package/dist/api/voice-settings-router.js.map +1 -1
- package/dist/build-provenance.json +4 -4
- package/dist/history/db.d.ts +4 -0
- package/dist/history/db.d.ts.map +1 -1
- package/dist/history/db.js +33 -5
- package/dist/history/db.js.map +1 -1
- package/dist/history/types.d.ts +1 -0
- package/dist/history/types.d.ts.map +1 -1
- package/dist/orchestration/channel-speech.d.ts +1 -1
- package/dist/orchestration/channel-speech.d.ts.map +1 -1
- package/dist/orchestration/channel-speech.js +2 -2
- package/dist/orchestration/channel-speech.js.map +1 -1
- package/dist/orchestration/config.d.ts +13 -0
- package/dist/orchestration/config.d.ts.map +1 -1
- package/dist/orchestration/config.js +6 -0
- package/dist/orchestration/config.js.map +1 -1
- package/dist/orchestration/dashboard-provider-wait.d.ts +9 -0
- package/dist/orchestration/dashboard-provider-wait.d.ts.map +1 -0
- package/dist/orchestration/dashboard-provider-wait.js +26 -0
- package/dist/orchestration/dashboard-provider-wait.js.map +1 -0
- package/dist/orchestration/dashboard-reader-worker.js +13 -6
- package/dist/orchestration/dashboard-reader-worker.js.map +1 -1
- package/dist/orchestration/delivery.d.ts +2 -1
- package/dist/orchestration/delivery.d.ts.map +1 -1
- package/dist/orchestration/delivery.js +39 -5
- package/dist/orchestration/delivery.js.map +1 -1
- package/dist/orchestration/file-delivery.d.ts +1 -1
- package/dist/orchestration/file-delivery.d.ts.map +1 -1
- package/dist/orchestration/file-delivery.js +8 -1
- package/dist/orchestration/file-delivery.js.map +1 -1
- package/dist/orchestration/gateway-config.js +1 -1
- package/dist/orchestration/gateway-config.js.map +1 -1
- package/dist/orchestration/line-quota.d.ts +57 -0
- package/dist/orchestration/line-quota.d.ts.map +1 -0
- package/dist/orchestration/line-quota.js +191 -0
- package/dist/orchestration/line-quota.js.map +1 -0
- package/dist/orchestration/process-turn.d.ts +1 -0
- package/dist/orchestration/process-turn.d.ts.map +1 -1
- package/dist/orchestration/process-turn.js +26 -6
- package/dist/orchestration/process-turn.js.map +1 -1
- package/dist/orchestration/provider-admission.d.ts +63 -0
- package/dist/orchestration/provider-admission.d.ts.map +1 -0
- package/dist/orchestration/provider-admission.js +175 -0
- package/dist/orchestration/provider-admission.js.map +1 -0
- package/dist/orchestration/provider-error-metadata.d.ts +9 -0
- package/dist/orchestration/provider-error-metadata.d.ts.map +1 -0
- package/dist/orchestration/provider-error-metadata.js +28 -0
- package/dist/orchestration/provider-error-metadata.js.map +1 -0
- package/dist/orchestration/provider-scope.d.ts +28 -0
- package/dist/orchestration/provider-scope.d.ts.map +1 -0
- package/dist/orchestration/provider-scope.js +137 -0
- package/dist/orchestration/provider-scope.js.map +1 -0
- package/dist/orchestration/runtime.d.ts +13 -0
- package/dist/orchestration/runtime.d.ts.map +1 -1
- package/dist/orchestration/runtime.js +217 -24
- package/dist/orchestration/runtime.js.map +1 -1
- package/dist/orchestration/store.d.ts +6 -0
- package/dist/orchestration/store.d.ts.map +1 -1
- package/dist/orchestration/store.js +51 -10
- package/dist/orchestration/store.js.map +1 -1
- package/dist/orchestration/tasks/driver.d.ts +5 -2
- package/dist/orchestration/tasks/driver.d.ts.map +1 -1
- package/dist/orchestration/tasks/driver.js +19 -5
- package/dist/orchestration/tasks/driver.js.map +1 -1
- package/dist/orchestration/tasks/scheduler.d.ts +12 -2
- package/dist/orchestration/tasks/scheduler.d.ts.map +1 -1
- package/dist/orchestration/tasks/scheduler.js +77 -7
- package/dist/orchestration/tasks/scheduler.js.map +1 -1
- package/dist/orchestration/tasks/service.d.ts +1 -1
- package/dist/orchestration/tasks/service.d.ts.map +1 -1
- package/dist/orchestration/tasks/service.js +11 -2
- package/dist/orchestration/tasks/service.js.map +1 -1
- package/dist/orchestration/types.d.ts +3 -0
- package/dist/orchestration/types.d.ts.map +1 -1
- package/dist/orchestration/types.js.map +1 -1
- package/dist/session/codex-process.d.ts +6 -0
- package/dist/session/codex-process.d.ts.map +1 -1
- package/dist/session/codex-process.js +63 -5
- package/dist/session/codex-process.js.map +1 -1
- package/dist/session/codex-runtime.d.ts.map +1 -1
- package/dist/session/codex-runtime.js +9 -1
- package/dist/session/codex-runtime.js.map +1 -1
- package/dist/share/share-store.d.ts +5 -11
- package/dist/share/share-store.d.ts.map +1 -1
- package/dist/share/share-store.js +33 -5
- package/dist/share/share-store.js.map +1 -1
- package/dist/ui/dashboard-client.d.ts.map +1 -1
- package/dist/ui/dashboard-client.js +7 -6
- package/dist/ui/dashboard-client.js.map +1 -1
- package/dist/ui/dashboard-presentation.d.ts +2 -0
- package/dist/ui/dashboard-presentation.d.ts.map +1 -1
- package/dist/ui/dashboard-presentation.js +15 -1
- package/dist/ui/dashboard-presentation.js.map +1 -1
- package/dist/ui/token-report.d.ts +6 -0
- package/dist/ui/token-report.d.ts.map +1 -1
- package/dist/ui/token-report.js +1 -1
- package/dist/ui/token-report.js.map +1 -1
- package/dist/voice/providers/paxalabs-live-stt.d.ts +29 -0
- package/dist/voice/providers/paxalabs-live-stt.d.ts.map +1 -0
- package/dist/voice/providers/paxalabs-live-stt.js +137 -0
- package/dist/voice/providers/paxalabs-live-stt.js.map +1 -0
- package/dist/voice/providers/registry.d.ts.map +1 -1
- package/dist/voice/providers/registry.js +2 -1
- package/dist/voice/providers/registry.js.map +1 -1
- package/mcp/tools/telegram/receiver-server.ts +7 -2
- package/package.json +1 -1
|
@@ -73,6 +73,8 @@ const capacity_1 = require("./capacity");
|
|
|
73
73
|
const cleanup_1 = require("./tasks/cleanup");
|
|
74
74
|
const task_files_1 = require("./task-files");
|
|
75
75
|
const worker_shares_1 = require("./worker-shares");
|
|
76
|
+
const provider_admission_1 = require("./provider-admission");
|
|
77
|
+
const provider_scope_1 = require("./provider-scope");
|
|
76
78
|
/** Stable instructions are carried in the system prefix, not appended to every
|
|
77
79
|
* resumed user turn. Per-turn authorization flags remain explicit below it. */
|
|
78
80
|
const GATEWAY_TASK_INSTRUCTIONS = 'For safemode discovery use capabilities_list(scope=safemode); this creates no task. For authorized work on a discovered session use task_spawn(target_profile=gateway-managed, gateway_target={adapter:safemode,session_id:...}). Gateway-managed tasks are followed by the gateway and report results automatically; never spawn a polling worker.';
|
|
@@ -126,7 +128,10 @@ class AgentOrchestrationRuntime {
|
|
|
126
128
|
this.taskControls = new task_controls_1.TaskControls(store, tasks);
|
|
127
129
|
this.stopControls = new stop_controls_1.StopControls(store, tasks, id => this.stopResponse(id));
|
|
128
130
|
this.channelControls = new channel_controls_1.ChannelControls(store, this.taskControls, this.stopControls, new telegram_voices_1.TelegramVoices(store, () => this.config.voice.tts, voice_catalog_1.voiceChoices, 8), () => (this.config.voice.enabled && this.config.voice.notes.replyWithVoice));
|
|
129
|
-
this.delivery = new delivery_1.DeliveryOutbox(store, (0, delivery_1.channelSender)(() => this.agent, fetch, (binding, speech) => Boolean(this.config.enabled && this.config.channels.includes(String(binding.channel)) && (this.config.voice.enabled && this.config.voice.notes.replyWithVoice) && (0, voice_reply_policy_1.voiceReplyAllowed)(store.channelVoiceMode(String(binding.channel), String(binding.chat_id), String(binding.thread_key ?? '')), speech.voiceOrigin === true) && (0, model_ref_1.canonicalVoiceProvider)(this.config.voice.tts.provider) === (0, model_ref_1.canonicalVoiceProvider)(speech.provider)), host.sendLinkedChannel
|
|
131
|
+
this.delivery = new delivery_1.DeliveryOutbox(store, (0, delivery_1.channelSender)(() => this.agent, fetch, (binding, speech) => Boolean(this.config.enabled && this.config.channels.includes(String(binding.channel)) && (this.config.voice.enabled && this.config.voice.notes.replyWithVoice) && (0, voice_reply_policy_1.voiceReplyAllowed)(store.channelVoiceMode(String(binding.channel), String(binding.chat_id), String(binding.thread_key ?? '')), speech.voiceOrigin === true) && (0, model_ref_1.canonicalVoiceProvider)(this.config.voice.tts.provider) === (0, model_ref_1.canonicalVoiceProvider)(speech.provider)), host.sendLinkedChannel,
|
|
132
|
+
// Includes 'processing' so the delivery that just 429'd (already claimed,
|
|
133
|
+
// no longer 'pending') still counts itself as part of the group needing quota.
|
|
134
|
+
() => Number(store.get(`SELECT COUNT(*) n FROM outbox o JOIN deliveries d ON d.id=json_extract(o.payload_json,'$.deliveryId') JOIN conversation_bindings b ON b.id=d.binding_id WHERE o.kind='delivery' AND o.state IN ('pending','processing') AND b.channel='line'`).n)));
|
|
130
135
|
this.decisions = new decisions_1.DecisionService(store, (response, binding, text) => {
|
|
131
136
|
this.delivery.enqueue(response, binding, text);
|
|
132
137
|
const spoken = store.get('SELECT text FROM response_speech WHERE response_id=?', response);
|
|
@@ -194,6 +199,7 @@ class AgentOrchestrationRuntime {
|
|
|
194
199
|
const personalRetention = (0, config_1.resolveDreamingConfig)(agent.dreaming, gateway.gateway.dreaming, gateway.gateway.timezone).staleness;
|
|
195
200
|
const sharedRetention = (0, knowledge_1.resolveSharedConfig)(agent.knowledge?.shared, gateway.gateway.knowledge?.shared).staleness;
|
|
196
201
|
bridge.recordRetrievals = (personalRetention.enabled && personalRetention.recordRetrievals) || (sharedRetention.enabled && sharedRetention.recordRetrievals);
|
|
202
|
+
let admissionStore;
|
|
197
203
|
try {
|
|
198
204
|
(0, recovery_1.recoverOrchestration)(store);
|
|
199
205
|
(0, session_compaction_1.recoverSessionCompaction)(store);
|
|
@@ -217,11 +223,49 @@ class AgentOrchestrationRuntime {
|
|
|
217
223
|
const workspaces = new workspace_1.TaskWorkspaces(store, project, (0, path_1.join)(root, 'task-worktrees'), agent.orchestration?.tasks?.workspaceMode);
|
|
218
224
|
for (const row of store.all("SELECT id FROM tasks WHERE state IN ('completed','failed','cancelled')"))
|
|
219
225
|
await workspaces.release(String(row.id));
|
|
220
|
-
const
|
|
221
|
-
const
|
|
226
|
+
const providerAdmission = admissionStore = new provider_admission_1.ProviderAdmissionStore((0, path_1.join)(sessions.getAgentsBaseDir(), 'provider-admission.db'));
|
|
227
|
+
const providerPolicy = () => runtime.config.providerAdmission;
|
|
228
|
+
const driver = workerDriver ?? new driver_1.ClaudeWorkerDriver(agent, gateway, tasks, bridge, workspaces, (0, path_1.join)(root, 'task-attempts'), host.onManagedTurn, (task, permit, harness, model, resolvedIdentity) => {
|
|
229
|
+
const actualAgent = { ...agent, workers: { ...agent.workers, harness } };
|
|
230
|
+
const scope = resolvedIdentity
|
|
231
|
+
? (0, provider_scope_1.resolvedCodexProviderScope)(resolvedIdentity, providerPolicy().recoveryGeneration)
|
|
232
|
+
: (0, provider_scope_1.resolveProviderScope)(actualAgent, gateway, model, 'worker', task.resourceProfile?.projectRoot);
|
|
233
|
+
const configured = (0, provider_scope_1.resolveProviderScope)(agent, gateway, task.model, 'worker', task.resourceProfile?.projectRoot);
|
|
234
|
+
store.run('INSERT INTO provider_task_routes VALUES(?,?,?) ON CONFLICT(task_id) DO UPDATE SET configured_scope=excluded.configured_scope,actual_scope=excluded.actual_scope', task.taskId, configured, scope);
|
|
235
|
+
if (scope === permit.scope)
|
|
236
|
+
return;
|
|
237
|
+
providerAdmission.release(permit);
|
|
238
|
+
const next = providerAdmission.acquire(scope, providerPolicy());
|
|
239
|
+
if (next.waiting) {
|
|
240
|
+
runtime.waitForProvider(task.taskId, task.conversationId, scope, next.waiting);
|
|
241
|
+
throw new types_2.OrchestrationError('PROVIDER_WAITING');
|
|
242
|
+
}
|
|
243
|
+
delete permit.probe;
|
|
244
|
+
Object.assign(permit, next.permit);
|
|
245
|
+
});
|
|
246
|
+
const scheduler = new scheduler_1.WorkerScheduler(tasks, driver, undefined, recoveredReservations, {
|
|
247
|
+
acquire: task => {
|
|
248
|
+
const configured = (0, provider_scope_1.resolveProviderScope)(agent, gateway, task.model, 'worker', task.resourceProfile?.projectRoot);
|
|
249
|
+
const previous = store.get('SELECT configured_scope,actual_scope FROM provider_task_routes WHERE task_id=?', task.taskId);
|
|
250
|
+
const scope = previous?.configured_scope === configured ? String(previous.actual_scope) : configured;
|
|
251
|
+
const result = providerAdmission.acquire(scope, providerPolicy());
|
|
252
|
+
if (result.waiting)
|
|
253
|
+
runtime.waitForProvider(task.taskId, task.conversationId, scope, result.waiting);
|
|
254
|
+
else
|
|
255
|
+
store.run('DELETE FROM provider_waits WHERE entity_id=?', task.taskId);
|
|
256
|
+
return result;
|
|
257
|
+
},
|
|
258
|
+
renew: permit => providerAdmission.renew(permit, providerPolicy()),
|
|
259
|
+
settle: (permit, result) => {
|
|
260
|
+
if (providerAdmission.settle(permit, result, providerPolicy()))
|
|
261
|
+
runtime.providerRecovered(permit.scope);
|
|
262
|
+
},
|
|
263
|
+
release: permit => providerAdmission.release(permit),
|
|
264
|
+
});
|
|
222
265
|
const cleanup = new cleanup_1.ResourceCleanup(store, (0, path_1.join)(root, 'task-worktrees'), (0, path_1.join)(root, 'task-artifacts'), (0, config_2.resolveOrchestrationConfig)(agent.orchestration).tasks.resourceRetentionDays);
|
|
223
266
|
const runtime = new AgentOrchestrationRuntime(agent, root, host, store, new history_1.OrchestrationHistoryWriter(store, sessions, historyDb), scheduler, bridge, tasks);
|
|
224
267
|
runtime.gateway = gateway;
|
|
268
|
+
runtime.providerAdmission = providerAdmission;
|
|
225
269
|
runtime.releaseLock = releaseLock;
|
|
226
270
|
runtime.settleResources = async () => { cleanup.stop(); await workspaces.settle(); await cleanup.settle(); };
|
|
227
271
|
const shared = (0, knowledge_1.resolveSharedConfig)(agent.knowledge?.shared, gateway.gateway.knowledge?.shared);
|
|
@@ -262,6 +306,7 @@ class AgentOrchestrationRuntime {
|
|
|
262
306
|
return runtime;
|
|
263
307
|
}
|
|
264
308
|
catch (error) {
|
|
309
|
+
admissionStore?.close();
|
|
265
310
|
await bridge.close();
|
|
266
311
|
store.close();
|
|
267
312
|
releaseLock();
|
|
@@ -277,14 +322,60 @@ class AgentOrchestrationRuntime {
|
|
|
277
322
|
if (!Number.isSafeInteger(after) || after < 0 || after > Number(conversation.last_event_seq))
|
|
278
323
|
throw new types_2.OrchestrationError('INVALID_CURSOR');
|
|
279
324
|
const tasks = this.tasks.status(id, principalId).map(t => {
|
|
280
|
-
return { taskId: t.taskId, title: t.title, state: t.state, stateVersion: t.stateVersion, progress: t.latestProgress, execution: t.execution, result: t.result?.summary, updatedAt: Math.max(t.updatedAt, t.execution?.lastActivityAt ?? 0) };
|
|
325
|
+
return { taskId: t.taskId, title: t.title, state: t.state, stateVersion: t.stateVersion, providerWaiting: t.providerWaiting, progress: t.latestProgress, execution: t.execution, result: t.result?.summary, updatedAt: Math.max(t.updatedAt, t.execution?.lastActivityAt ?? 0) };
|
|
281
326
|
});
|
|
282
327
|
const responses = this.store.all('SELECT id,request_id,state,generated_text,COALESCE(completed_at,created_at) AS message_at FROM assistant_responses WHERE conversation_id=? ORDER BY message_at DESC,rowid DESC LIMIT 100', id).reverse().map(r => ({
|
|
283
328
|
id: r.id, requestId: r.request_id, state: r.state, text: r.generated_text, createdAt: r.message_at,
|
|
284
329
|
files: this.store.all('SELECT path FROM task_files WHERE response_id=? ORDER BY created_at,id', r.id).map(f => f.path),
|
|
285
330
|
}));
|
|
286
331
|
const tools = this.store.all("SELECT seq,payload_json FROM conversation_events WHERE conversation_id=? AND seq>? AND type='tool.activity' ORDER BY seq LIMIT 500", id, after).map(r => ({ seq: r.seq, ...JSON.parse(String(r.payload_json)).payload }));
|
|
287
|
-
|
|
332
|
+
const waiting = this.store.get('SELECT waiting_json FROM provider_waits WHERE entity_id=?', `session:${sessionId}`);
|
|
333
|
+
return { cursor: tools.length === 500 ? tools[tools.length - 1].seq : Number(conversation.last_event_seq), tasks, responses, tools, busy: this.isBusy(sessionId), providerWaiting: waiting ? JSON.parse(String(waiting.waiting_json)) : undefined };
|
|
334
|
+
}
|
|
335
|
+
waitForProvider(entity, conversationId, scope, waiting) {
|
|
336
|
+
const previous = this.store.get('SELECT waiting_json FROM provider_waits WHERE entity_id=?', entity);
|
|
337
|
+
const data = JSON.stringify(waiting);
|
|
338
|
+
let text = '';
|
|
339
|
+
let changed = false;
|
|
340
|
+
this.store.compose(() => {
|
|
341
|
+
if (previous?.waiting_json !== data) {
|
|
342
|
+
changed = true;
|
|
343
|
+
this.store.run('INSERT INTO provider_waits VALUES(?,?,?,?,?) ON CONFLICT(entity_id) DO UPDATE SET scope=excluded.scope,waiting_json=excluded.waiting_json,updated_at=excluded.updated_at', entity, conversationId, scope, data, Date.now());
|
|
344
|
+
this.store.appendEvent(conversationId, 'provider.waiting', { entity, ...waiting });
|
|
345
|
+
}
|
|
346
|
+
const notice = this.store.get('SELECT episode FROM provider_notices WHERE conversation_id=? AND scope=?', conversationId, scope);
|
|
347
|
+
if (notice?.episode !== waiting.episode) {
|
|
348
|
+
text = waiting.requiresConfigurationChange
|
|
349
|
+
? 'Waiting for provider. Check the provider credentials, model or quota. Your pending messages and task results are saved.'
|
|
350
|
+
: 'Waiting for provider. Your pending messages and task results are saved. I will retry automatically after the cooldown.';
|
|
351
|
+
const response = this.decisions.notice(conversationId, text, true);
|
|
352
|
+
this.store.run('INSERT INTO provider_notices VALUES(?,?,?,0) ON CONFLICT(conversation_id,scope) DO UPDATE SET episode=excluded.episode,recovered=0', conversationId, scope, waiting.episode);
|
|
353
|
+
const session = this.store.get('SELECT agent_session_id FROM conversations WHERE id=?', conversationId);
|
|
354
|
+
if (session)
|
|
355
|
+
this.publishText(String(session.agent_session_id), response, text, true);
|
|
356
|
+
}
|
|
357
|
+
});
|
|
358
|
+
if (changed || text) {
|
|
359
|
+
void this.flushHistory().catch(() => { });
|
|
360
|
+
void this.delivery.tick().catch(() => { });
|
|
361
|
+
}
|
|
362
|
+
return text;
|
|
363
|
+
}
|
|
364
|
+
providerRecovered(scope) {
|
|
365
|
+
this.store.compose(() => {
|
|
366
|
+
this.store.run('DELETE FROM provider_waits WHERE scope=?', scope);
|
|
367
|
+
for (const conversation of this.store.all(`SELECT n.conversation_id,c.agent_session_id FROM provider_notices n
|
|
368
|
+
JOIN conversations c ON c.id=n.conversation_id WHERE n.scope=? AND n.recovered=0 AND c.status='active'`, scope)) {
|
|
369
|
+
const conversationId = String(conversation.conversation_id), sessionId = String(conversation.agent_session_id);
|
|
370
|
+
this.store.run('UPDATE provider_notices SET recovered=1 WHERE conversation_id=? AND scope=?', conversationId, scope);
|
|
371
|
+
this.store.appendEvent(conversationId, 'provider.recovered', {});
|
|
372
|
+
const text = 'The provider is responding again. Pending messages and task reports can continue.';
|
|
373
|
+
const response = this.decisions.notice(conversationId, text, true);
|
|
374
|
+
this.publishText(sessionId, response, text, true);
|
|
375
|
+
}
|
|
376
|
+
});
|
|
377
|
+
void this.flushHistory().catch(() => { });
|
|
378
|
+
void this.delivery.tick().catch(() => { });
|
|
288
379
|
}
|
|
289
380
|
isBusy(sessionId) { return this.active.has(sessionId); }
|
|
290
381
|
isCompacting(sessionId) { return this.active.get(sessionId)?.maintenance === 'compact'; }
|
|
@@ -340,6 +431,7 @@ class AgentOrchestrationRuntime {
|
|
|
340
431
|
if (this.agent.type !== 'app-agent' && config?.tasks?.workspaceMode === 'container')
|
|
341
432
|
throw new types_2.OrchestrationError('CONTAINER_REQUIRED');
|
|
342
433
|
this.config = (0, config_2.resolveOrchestrationConfig)(config, backendAgent.voice ?? { enabled: false });
|
|
434
|
+
this.agent.orchestration = config;
|
|
343
435
|
this.tasks.configure(config);
|
|
344
436
|
if (!this.config.enabled)
|
|
345
437
|
this.drain();
|
|
@@ -695,6 +787,7 @@ class AgentOrchestrationRuntime {
|
|
|
695
787
|
}
|
|
696
788
|
return receipt;
|
|
697
789
|
});
|
|
790
|
+
void this.flushHistory().catch(() => { });
|
|
698
791
|
if (this.config.conversation.semanticIntake)
|
|
699
792
|
this.intake.touch(receipt.inputId);
|
|
700
793
|
const previous = this.inputResponses.get(receipt.inputId);
|
|
@@ -741,6 +834,12 @@ class AgentOrchestrationRuntime {
|
|
|
741
834
|
if (Date.now() >= this.nextQuestionCheck) {
|
|
742
835
|
this.questionControls.tick();
|
|
743
836
|
this.nextQuestionCheck = Date.now() + 1000;
|
|
837
|
+
// A sibling agent or a worker can recover the shared circuit without a
|
|
838
|
+
// conversation turn here. Deliver its notices through the same outbox.
|
|
839
|
+
for (const row of this.store.all('SELECT DISTINCT scope FROM provider_notices WHERE recovered=0 LIMIT 100')) {
|
|
840
|
+
if (this.providerAdmission.recovered(String(row.scope)))
|
|
841
|
+
this.providerRecovered(String(row.scope));
|
|
842
|
+
}
|
|
744
843
|
}
|
|
745
844
|
for (const conversation of this.questionControls.initialReviews([...this.active.keys()])) {
|
|
746
845
|
this.store.compose(() => {
|
|
@@ -763,25 +862,46 @@ class AgentOrchestrationRuntime {
|
|
|
763
862
|
ingressKey: `notification:${row.notification_id}${row.previous_input_id ? `:retry:${row.previous_seq}` : ''}`, capabilities: { execute: false, writeMemory: false } }, this.config.conversation.maxPendingInputs);
|
|
764
863
|
}
|
|
765
864
|
}
|
|
766
|
-
|
|
767
|
-
|
|
865
|
+
let mailboxCursor = 0;
|
|
866
|
+
const visitedSessions = new Set();
|
|
867
|
+
mailbox: while (this.active.size < this.config.conversation.maxActiveSessions) {
|
|
868
|
+
const rows = this.store.all("SELECT i.*,i.rowid AS mailbox_row FROM conversation_inputs i JOIN conversations c ON c.id=i.conversation_id WHERE i.status='accepted' AND i.rowid>? AND c.agent_session_id NOT IN (SELECT value FROM json_each(?)) ORDER BY i.rowid LIMIT 100", mailboxCursor, JSON.stringify([...this.active.keys()]));
|
|
869
|
+
if (!rows.length)
|
|
768
870
|
break;
|
|
769
|
-
const
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
871
|
+
for (const row of rows) {
|
|
872
|
+
mailboxCursor = Number(row.mailbox_row);
|
|
873
|
+
if (this.active.size >= this.config.conversation.maxActiveSessions)
|
|
874
|
+
break;
|
|
875
|
+
const input = JSON.parse(String(row.ingress_json));
|
|
876
|
+
if (!input.scope || !input.capabilities || this.active.has(input.scope.agentSessionId))
|
|
877
|
+
continue;
|
|
878
|
+
if (visitedSessions.has(input.scope.agentSessionId))
|
|
879
|
+
continue;
|
|
880
|
+
visitedSessions.add(input.scope.agentSessionId);
|
|
881
|
+
const scope = (0, provider_scope_1.resolveProviderScope)(this.agent, this.gateway, input.model, 'agent');
|
|
882
|
+
const waiting = this.providerAdmission.inspect(scope, this.config.providerAdmission);
|
|
883
|
+
if (waiting) {
|
|
884
|
+
const text = this.waitForProvider(`session:${input.scope.agentSessionId}`, String(row.conversation_id), scope, waiting);
|
|
885
|
+
if (text)
|
|
886
|
+
this.deferred.get(String(row.id))?.resolve(text);
|
|
887
|
+
continue;
|
|
888
|
+
}
|
|
889
|
+
// A persisted input retains the authenticated scope and model from ingress.
|
|
890
|
+
// Recovery can repeat inference, but committed tool receipts remain fenced.
|
|
891
|
+
const result = this.send({ ...input, acceptedInputId: String(row.id) }, input.capabilities, { timeoutMs: this.config.conversation.maxDecisionDurationMs, model: input.model, onTool: event => this.inputTools.get(String(row.id))?.(event), onText: text => {
|
|
892
|
+
const responseId = this.responseIdForInput(String(row.id));
|
|
893
|
+
if (input.modality !== 'live_voice' && responseId) {
|
|
894
|
+
try {
|
|
895
|
+
this.inputStreams.get(String(row.id))?.push({ responseId, text });
|
|
896
|
+
}
|
|
897
|
+
catch { /* slow audio cannot stall inference */ }
|
|
779
898
|
}
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
899
|
+
} });
|
|
900
|
+
void result.then(text => this.deferred.get(String(row.id))?.resolve(text), error => this.deferred.get(String(row.id))?.reject(error))
|
|
901
|
+
.finally(() => this.deferred.delete(String(row.id)));
|
|
902
|
+
}
|
|
903
|
+
if (this.active.size >= this.config.conversation.maxActiveSessions)
|
|
904
|
+
break mailbox;
|
|
785
905
|
}
|
|
786
906
|
}
|
|
787
907
|
async run(input, capabilities, options) {
|
|
@@ -801,13 +921,29 @@ class AgentOrchestrationRuntime {
|
|
|
801
921
|
const questionReview = Boolean(input.ingressKey?.startsWith('question-review:'));
|
|
802
922
|
let internalReview = false;
|
|
803
923
|
let streamedDisplay = '';
|
|
924
|
+
let providerPermit;
|
|
925
|
+
let providerRenewal;
|
|
804
926
|
try {
|
|
805
927
|
const receipt = this.store.acceptInput(input, this.config.conversation.maxPendingInputs);
|
|
928
|
+
await this.flushHistory();
|
|
806
929
|
if (this.config.conversation.semanticIntake)
|
|
807
930
|
this.intake.touch(receipt.inputId);
|
|
808
931
|
const admitted = this.store.get('SELECT ingress_json,binding_id FROM conversation_inputs WHERE id=?', receipt.inputId);
|
|
809
932
|
const admittedModel = admitted ? JSON.parse(String(admitted.ingress_json)).model : undefined;
|
|
810
|
-
options = { ...options, model: options.model ?? admittedModel ?? input.model };
|
|
933
|
+
options = { ...options, model: options.model ?? admittedModel ?? input.model ?? this.agent.claude.model };
|
|
934
|
+
const providerScope = (0, provider_scope_1.resolveProviderScope)(this.agent, this.gateway, options.model, 'agent');
|
|
935
|
+
const provider = this.providerAdmission.acquire(providerScope, this.config.providerAdmission);
|
|
936
|
+
if (provider.waiting)
|
|
937
|
+
return this.waitForProvider(`session:${sessionId}`, receipt.conversationId, providerScope, provider.waiting);
|
|
938
|
+
providerPermit = provider.permit;
|
|
939
|
+
this.store.run('DELETE FROM provider_waits WHERE entity_id=?', `session:${sessionId}`);
|
|
940
|
+
if (providerPermit.probe) {
|
|
941
|
+
providerRenewal = setInterval(() => { try {
|
|
942
|
+
this.providerAdmission.renew(providerPermit, this.config.providerAdmission);
|
|
943
|
+
}
|
|
944
|
+
catch { /* durable lease expires conservatively */ } }, Math.max(250, Math.floor(this.config.providerAdmission.probeLeaseMs / 3)));
|
|
945
|
+
providerRenewal.unref();
|
|
946
|
+
}
|
|
811
947
|
if (this.draining)
|
|
812
948
|
this.store.run("UPDATE conversations SET status='draining' WHERE id=?", receipt.conversationId);
|
|
813
949
|
this.seenSessions.add(sessionId);
|
|
@@ -1233,7 +1369,23 @@ class AgentOrchestrationRuntime {
|
|
|
1233
1369
|
displayChunk(chunk);
|
|
1234
1370
|
});
|
|
1235
1371
|
active.turn = turn;
|
|
1372
|
+
let providerResponded = false;
|
|
1373
|
+
void turn.providerReady.then(() => {
|
|
1374
|
+
providerResponded = true;
|
|
1375
|
+
try {
|
|
1376
|
+
if (!active.stopping && this.providerAdmission.settle(providerPermit, 'success', this.config.providerAdmission))
|
|
1377
|
+
this.providerRecovered(providerPermit.scope);
|
|
1378
|
+
}
|
|
1379
|
+
catch { /* Never turn a successful inference into a failed task receipt. */ }
|
|
1380
|
+
}).catch(() => { });
|
|
1236
1381
|
const response = await turn.result;
|
|
1382
|
+
if (!response.interrupted && !providerResponded) {
|
|
1383
|
+
try {
|
|
1384
|
+
if (this.providerAdmission.settle(providerPermit, 'success', this.config.providerAdmission))
|
|
1385
|
+
this.providerRecovered(providerPermit.scope);
|
|
1386
|
+
}
|
|
1387
|
+
catch { /* Provider bookkeeping cannot invalidate a completed inference. */ }
|
|
1388
|
+
}
|
|
1237
1389
|
if (!response.interrupted) {
|
|
1238
1390
|
// A completed CLI turn has consumed its tool results. Failed/interrupted
|
|
1239
1391
|
// turns never advance this checkpoint, so committed receipts can recover.
|
|
@@ -1307,6 +1459,13 @@ class AgentOrchestrationRuntime {
|
|
|
1307
1459
|
? (speechEnabled || active.stopReason === 'barge-in' || parsed.outcome !== 'structured' ? stoppedDisplay : surfaces.display || 'Response stopped.')
|
|
1308
1460
|
: surfaces.display || '';
|
|
1309
1461
|
this.decisions.finish(decision, display, response.interrupted ? 'interrupted' : 'completed', channelSpeech && !silent ? taskSpeech || surfaces.spoken : undefined, !active.stopping && !silent);
|
|
1462
|
+
if (active.notification && !response.interrupted) {
|
|
1463
|
+
const batch = this.store.get('SELECT COUNT(*)-COUNT(DISTINCT task_id) n FROM notifications WHERE decision_id=?', decision.decisionId);
|
|
1464
|
+
try {
|
|
1465
|
+
this.providerAdmission.coalesced(Number(batch?.n ?? 0));
|
|
1466
|
+
}
|
|
1467
|
+
catch { /* telemetry cannot invalidate a report */ }
|
|
1468
|
+
}
|
|
1310
1469
|
if (!silent && speechEnabled && !response.interrupted && !taskSpeech) {
|
|
1311
1470
|
if (!channelSpeech)
|
|
1312
1471
|
this.store.run('INSERT INTO response_speech VALUES(?,?)', decision.responseId, surfaces.spoken);
|
|
@@ -1351,6 +1510,15 @@ class AgentOrchestrationRuntime {
|
|
|
1351
1510
|
return silent ? acknowledgement : display || acknowledgement;
|
|
1352
1511
|
}
|
|
1353
1512
|
catch (error) {
|
|
1513
|
+
if (providerPermit && active.turn && !active.stopping) {
|
|
1514
|
+
const failure = (0, provider_admission_1.providerFailure)(error);
|
|
1515
|
+
if (failure) {
|
|
1516
|
+
try {
|
|
1517
|
+
this.providerAdmission.settle(providerPermit, failure, this.config.providerAdmission);
|
|
1518
|
+
}
|
|
1519
|
+
catch { /* Preserve original error and cleanup even when shared storage is busy. */ }
|
|
1520
|
+
}
|
|
1521
|
+
}
|
|
1354
1522
|
// Retain a safe diagnostic code; never log prompts, credentials or provider bodies.
|
|
1355
1523
|
failedTurn = true;
|
|
1356
1524
|
const failure = error;
|
|
@@ -1404,6 +1572,14 @@ class AgentOrchestrationRuntime {
|
|
|
1404
1572
|
throw error;
|
|
1405
1573
|
}
|
|
1406
1574
|
finally {
|
|
1575
|
+
if (providerRenewal)
|
|
1576
|
+
clearInterval(providerRenewal);
|
|
1577
|
+
if (providerPermit) {
|
|
1578
|
+
try {
|
|
1579
|
+
this.providerAdmission.release(providerPermit);
|
|
1580
|
+
}
|
|
1581
|
+
catch { /* lease expires; process cleanup must still run */ }
|
|
1582
|
+
}
|
|
1407
1583
|
removeContextObserver?.();
|
|
1408
1584
|
revoke?.();
|
|
1409
1585
|
if (agentSession)
|
|
@@ -1419,7 +1595,23 @@ class AgentOrchestrationRuntime {
|
|
|
1419
1595
|
}
|
|
1420
1596
|
stopResponse(sessionId, reason = 'user') {
|
|
1421
1597
|
const active = this.active.get(sessionId);
|
|
1422
|
-
if (!active
|
|
1598
|
+
if (!active) {
|
|
1599
|
+
if (reason !== 'user' || !this.store.get('SELECT entity_id FROM provider_waits WHERE entity_id=?', `session:${sessionId}`))
|
|
1600
|
+
return false;
|
|
1601
|
+
let stopped = false;
|
|
1602
|
+
for (const row of this.store.all("SELECT i.* FROM conversation_inputs i JOIN conversations c ON c.id=i.conversation_id WHERE c.agent_session_id=? AND i.status='accepted' ORDER BY i.input_seq", sessionId)) {
|
|
1603
|
+
const decision = this.decisions.begin(String(row.conversation_id), String(row.principal_id), [String(row.id)], row.request_id ? String(row.request_id) : undefined);
|
|
1604
|
+
this.decisions.interrupt(decision);
|
|
1605
|
+
this.decisions.finish(decision, '', 'interrupted', undefined, false);
|
|
1606
|
+
this.deferred.get(String(row.id))?.resolve('Response stopped.');
|
|
1607
|
+
this.deferred.delete(String(row.id));
|
|
1608
|
+
stopped = true;
|
|
1609
|
+
}
|
|
1610
|
+
this.store.run('DELETE FROM provider_waits WHERE entity_id=?', `session:${sessionId}`);
|
|
1611
|
+
void this.flushHistory().catch(() => { });
|
|
1612
|
+
return stopped;
|
|
1613
|
+
}
|
|
1614
|
+
if (active.stopping)
|
|
1423
1615
|
return false;
|
|
1424
1616
|
active.stopping = true;
|
|
1425
1617
|
active.stopReason = reason;
|
|
@@ -1472,6 +1664,7 @@ class AgentOrchestrationRuntime {
|
|
|
1472
1664
|
// Caller waits for pending conversational responses before releasing store.
|
|
1473
1665
|
if (this.active.size)
|
|
1474
1666
|
throw new types_2.OrchestrationError('ACTIVE_DECISIONS_DURING_SHUTDOWN');
|
|
1667
|
+
this.providerAdmission.close();
|
|
1475
1668
|
this.store.close();
|
|
1476
1669
|
this.releaseLock();
|
|
1477
1670
|
}
|