@awak-app/simy-cli 0.7.20 → 0.7.21
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 +57 -12
- package/package.json +1 -1
- package/src/cli-contract.js +1 -1
- package/src/codex-plugins/simy/hooks/delivery-loop.mjs +9 -1
- package/src/codex-work-pattern-sync.js +243 -43
- package/src/console/sessions.js +6 -6
- package/src/delivery-hooks/command.js +8 -6
- package/src/delivery-hooks/lifecycle-recovery.js +82 -0
- package/src/delivery-hooks/local-supervisor.js +25 -2
- package/src/delivery-hooks/supervisor-activation.js +25 -0
- package/src/delivery-hooks/supervisor-service.js +2 -2
- package/src/delivery-hooks/supervisor-watchdog.js +11 -6
- package/src/desktop-host.js +19 -5
- package/src/index.js +1 -1
- package/src/session-supervision/claude-sessions.js +7 -7
- package/src/session-supervision/codex-app-server.js +19 -9
- package/src/session-supervision/codex-peer-opinion.js +128 -0
- package/src/session-supervision/index.js +21 -12
- package/src/session-supervision/remote-control.js +27 -0
- package/src/session-supervision/remote-errors.js +22 -0
- package/src/session-supervision/remote-hosts.js +17 -13
- package/src/session-supervision/remote-session-list.js +56 -0
- package/src/session-supervision/session-list.js +83 -23
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { automaticContinuationAllowed, hasPendingUserStop, queuePurposeDiagnosis,
|
|
2
|
+
updateRecord, advanceDeliveryControlRevision } from '../codex-plugins/simy/hooks/delivery-loop.mjs';
|
|
3
|
+
import { requireProviderLink } from '../provider-links.js';
|
|
4
|
+
import { openCodexAppServer, readCodexObservation } from '../session-supervision/codex-app-server.js';
|
|
5
|
+
|
|
6
|
+
function eligible(record) {
|
|
7
|
+
const run = record?.run, managed = run?.managed;
|
|
8
|
+
if (record?.provider !== 'codex' || record.autoContinue !== true || !automaticContinuationAllowed(record) ||
|
|
9
|
+
!managed?.purpose?.enabled || managed.resumeChannel !== 'codex_app_server' ||
|
|
10
|
+
!['active', 'recovery_required', 'blocked'].includes(run.state) || run.stopReason?.actor === 'user' ||
|
|
11
|
+
managed.resumeLease || managed.liveWorkspaceLease || managed.outcomeAudit?.lease ||
|
|
12
|
+
managed.nativeWait || managed.purpose.nativeBoundary || managed.providerWarning ||
|
|
13
|
+
managed.userQuestion || managed.understandingQuestion || managed.dependencyWait ||
|
|
14
|
+
managed.authenticationWait || managed.phase === 'understanding' || managed.usageBlocked) return false;
|
|
15
|
+
// A restart is never approval for an effect. Only a controller-generated
|
|
16
|
+
// local context-selection wait can yield to independent read diagnosis.
|
|
17
|
+
const pending = managed.pendingApproval;
|
|
18
|
+
if (pending && (pending.denied || pending.kind !== 'scope_change' || managed.decision?.assessment?.externalEffect !== 'local' ||
|
|
19
|
+
managed.decision.assessment.reversibility !== 'reversible' || managed.decision.assessment.inObjective !== true ||
|
|
20
|
+
managed.decision.assessment.userChoice !== false)) return false;
|
|
21
|
+
return true;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// Called once by the owning supervisor after a durable activation is loaded.
|
|
25
|
+
// It preserves the same run, purpose, budgets and effect history, and queues a
|
|
26
|
+
// read. An interrupted write is reconciled before any proposal to repeat it.
|
|
27
|
+
export async function reconcileLifecycleRecovery({ root, records, eventId, authorize = async () => {}, sessionEndedAt }) {
|
|
28
|
+
for (const record of records) {
|
|
29
|
+
if (!eligible(record) || hasPendingUserStop(root, record)) continue;
|
|
30
|
+
try {
|
|
31
|
+
const link = await requireProviderLink({ root, provider: record.provider });
|
|
32
|
+
await authorize(record);
|
|
33
|
+
await updateRecord(root, record.provider, record.session, async current => {
|
|
34
|
+
if (!eligible(current) || hasPendingUserStop(root, current) || current.run.id !== record.run.id ||
|
|
35
|
+
current.run.revision !== record.run.revision || current.run.controlRevision !== record.run.controlRevision ||
|
|
36
|
+
current.autoContinueEpoch !== record.autoContinueEpoch || current.run.managed.lifecycleRecovery?.eventId === eventId ||
|
|
37
|
+
sessionEndedAt !== undefined && !endedSession(current, sessionEndedAt)) return current;
|
|
38
|
+
await requireProviderLink({ root, provider: record.provider, expectedEpoch: link.epoch });
|
|
39
|
+
await authorize(current);
|
|
40
|
+
const run = current.run, managed = run.managed, previousState = run.state;
|
|
41
|
+
const pending = managed.pendingApproval ? structuredClone(managed.pendingApproval) : null;
|
|
42
|
+
const queued = queuePurposeDiagnosis(run,
|
|
43
|
+
'The provider session ended or the local execution host returned after an interruption. Read the saved task and actual current artifacts first. Keep the original goal, corrections, permission ceiling, budgets and explicit stops. Reconcile unfinished or uncertain effects before proposing more work; do not replay a prior write or treat recovery as approval. Inspect the current execution context and choose useful authorized work.',
|
|
44
|
+
`lifecycle:${eventId}`, Date.now(), 'interrupted_owner');
|
|
45
|
+
if (queued) {
|
|
46
|
+
managed.lifecycleRecovery = { eventId, at: Date.now(), previousState, mode: 'read_before_continue', retainedApproval: pending };
|
|
47
|
+
advanceDeliveryControlRevision(run);
|
|
48
|
+
run.updatedAt = Date.now();
|
|
49
|
+
}
|
|
50
|
+
return current;
|
|
51
|
+
});
|
|
52
|
+
} catch (error) {
|
|
53
|
+
if (['provider_link_disconnected', 'provider_link_changed'].includes(error.code) ||
|
|
54
|
+
/^Delivery state (?:is busy; retry the command\.|lock owner is unavailable; inspect the lock before retrying\.)$/.test(error.message)) continue;
|
|
55
|
+
throw error;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function endedSession(record, at = record.hookEndedAt) {
|
|
61
|
+
return record.lastEvent === 'SessionEnd' && Number.isFinite(at) && at > 0 && record.hookEndedAt === at &&
|
|
62
|
+
record.run?.state === 'recovery_required' && record.run.recoveryCause === 'session_end';
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async function observeEndedSession(record) {
|
|
66
|
+
const client = await openCodexAppServer();
|
|
67
|
+
try { return await readCodexObservation(client, record.session); }
|
|
68
|
+
finally { await client.close(); }
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// A provider can end while the supervisor remains alive. Reconcile each such
|
|
72
|
+
// event once, after confirming the original conversation has no active turn.
|
|
73
|
+
export async function reconcileEndedSessions({ root, records, eventId, authorize, observe = observeEndedSession }) {
|
|
74
|
+
for (const record of records) {
|
|
75
|
+
if (!endedSession(record) || !eligible(record) || hasPendingUserStop(root, record)) continue;
|
|
76
|
+
let observation;
|
|
77
|
+
try { observation = await observe(record); } catch { continue; }
|
|
78
|
+
if (observation?.isRunning !== false) continue;
|
|
79
|
+
await reconcileLifecycleRecovery({ root, records: [record], authorize,
|
|
80
|
+
eventId: `${eventId}:session-end:${record.session}:${record.hookEndedAt}`, sessionEndedAt: record.hookEndedAt });
|
|
81
|
+
}
|
|
82
|
+
}
|
|
@@ -1,4 +1,8 @@
|
|
|
1
|
-
import { dirname } from 'node:path';
|
|
1
|
+
import { dirname, join } from 'node:path';
|
|
2
|
+
import { listRecords } from '../codex-plugins/simy/hooks/delivery-loop.mjs';
|
|
3
|
+
import { readSupervisorState } from './supervisor-owner.js';
|
|
4
|
+
import { supervisorTargetMatches } from './supervisor-activation.js';
|
|
5
|
+
import { reconcileLifecycleRecovery, reconcileEndedSessions } from './lifecycle-recovery.js';
|
|
2
6
|
import { setTimeout as delay } from 'node:timers/promises';
|
|
3
7
|
import { assertNoDesktopHostForOrigin } from '../desktop-process-lock.js';
|
|
4
8
|
import { createManagedSupervisor } from './supervisor.js';
|
|
@@ -6,6 +10,8 @@ import { acquireSupervisorOwner } from './supervisor-owner.js';
|
|
|
6
10
|
import { pendingSupervisorHandover, acknowledgeSupervisorDrain } from './supervisor-handover.js';
|
|
7
11
|
|
|
8
12
|
export async function superviseLocalDelivery({ root, webOrigin, once = false, signal,
|
|
13
|
+
activationEpoch, readActivation = readSupervisorState, reconcileStartup = reconcileLifecycleRecovery,
|
|
14
|
+
reconcileSessionEnds = reconcileEndedSessions,
|
|
9
15
|
createSupervisor = createManagedSupervisor, checkOwner = assertNoDesktopHostForOrigin, wait = delay,
|
|
10
16
|
acquireOwner = acquireSupervisorOwner, pendingHandover = pendingSupervisorHandover,
|
|
11
17
|
acknowledgeDrain = acknowledgeSupervisorDrain } = {}) {
|
|
@@ -16,13 +22,28 @@ export async function superviseLocalDelivery({ root, webOrigin, once = false, si
|
|
|
16
22
|
const owner = await acquireOwner(dirname(root), { handoverVersion: 1 });
|
|
17
23
|
try {
|
|
18
24
|
await check();
|
|
25
|
+
const activationFile = join(dirname(root), 'supervisor-runtime/control.json');
|
|
26
|
+
const activation = activationEpoch ? await readActivation(activationFile) : null;
|
|
27
|
+
const activationCurrent = value => value?.version === 1 && value.enabled === true && value.epoch === activationEpoch;
|
|
28
|
+
if (activationEpoch && !activationCurrent(activation)) return;
|
|
29
|
+
const authorizeDispatch = async record => {
|
|
30
|
+
const current = await readActivation(activationFile);
|
|
31
|
+
if (!activationCurrent(current) || !supervisorTargetMatches(current, record)) throw new Error('Supervisor activation or target changed.');
|
|
32
|
+
return activationEpoch;
|
|
33
|
+
};
|
|
34
|
+
const readRecords = async () => (await listRecords(root)).filter(record => supervisorTargetMatches(activation, record));
|
|
35
|
+
if (activationEpoch) await reconcileStartup({ root, records: await readRecords(),
|
|
36
|
+
eventId: `${activationEpoch}:${owner.nonce}`, authorize: authorizeDispatch });
|
|
19
37
|
const supervisor = createSupervisor({ root, webOrigin,
|
|
20
|
-
|
|
38
|
+
...(activationEpoch ? { readRecords, authorizeDispatch } : {}),
|
|
39
|
+
shouldYield: async () => Boolean(activationEpoch && !activationCurrent(await readActivation(activationFile)) ||
|
|
40
|
+
await pendingHandover(dirname(root), owner.nonce)) });
|
|
21
41
|
const stop = () => { void supervisor.close(); };
|
|
22
42
|
signal?.addEventListener('abort', stop, { once: true });
|
|
23
43
|
try {
|
|
24
44
|
do {
|
|
25
45
|
if (signal?.aborted) break;
|
|
46
|
+
if (activationEpoch && !activationCurrent(await readActivation(activationFile))) break;
|
|
26
47
|
const handover = await pendingHandover(dirname(root), owner.nonce);
|
|
27
48
|
if (handover) {
|
|
28
49
|
await supervisor.drain();
|
|
@@ -30,6 +51,8 @@ export async function superviseLocalDelivery({ root, webOrigin, once = false, si
|
|
|
30
51
|
break;
|
|
31
52
|
}
|
|
32
53
|
await check();
|
|
54
|
+
if (activationEpoch) await reconcileSessionEnds({ root, records: await readRecords(),
|
|
55
|
+
eventId: activationEpoch, authorize: authorizeDispatch });
|
|
33
56
|
await supervisor.tick();
|
|
34
57
|
if (once) { await supervisor.idle?.(); break; }
|
|
35
58
|
try { await wait(3_000, undefined, { signal }); }
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { join } from 'node:path';
|
|
2
|
+
import { readRecord, automaticContinuationAllowed } from '../codex-plugins/simy/hooks/delivery-loop.mjs';
|
|
3
|
+
|
|
4
|
+
// Activation is durable OS recovery consent, separate from task permissions.
|
|
5
|
+
// A scoped activation binds the existing run/consent, never a future task that
|
|
6
|
+
// happens to reuse the conversation id.
|
|
7
|
+
export async function supervisorTarget(root, target) {
|
|
8
|
+
if (!target || !['codex', 'claude'].includes(target.provider) || typeof target.session !== 'string' || !target.session) {
|
|
9
|
+
throw new Error('Select an exact provider and session for supervisor recovery.');
|
|
10
|
+
}
|
|
11
|
+
const record = await readRecord(join(root, 'delivery-hooks'), target.provider, target.session);
|
|
12
|
+
if (!record?.run?.managed || record.autoContinue !== true || !record.autoContinueEpoch ||
|
|
13
|
+
!automaticContinuationAllowed(record) || ['stopped', 'paused', 'completed', 'reported_done', 'budget_exhausted'].includes(record.run.state)) {
|
|
14
|
+
throw new Error('Supervisor activation requires an existing opted-in task; explicit task stops remain stopped.');
|
|
15
|
+
}
|
|
16
|
+
return { provider: record.provider, session: record.session, runId: record.run.id, autoContinueEpoch: record.autoContinueEpoch };
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function supervisorTargetMatches(control, record) {
|
|
20
|
+
if (!Object.hasOwn(control || {}, 'targets')) return true;
|
|
21
|
+
return Array.isArray(control.targets) && control.targets.some(target =>
|
|
22
|
+
target.provider === record.provider && target.session === record.session &&
|
|
23
|
+
typeof target.runId === 'string' && target.runId === record.run?.id &&
|
|
24
|
+
typeof target.autoContinueEpoch === 'string' && target.autoContinueEpoch === record.autoContinueEpoch);
|
|
25
|
+
}
|
|
@@ -24,12 +24,12 @@ export function supervisorServiceDefinition({ root, entry, node = process.execPa
|
|
|
24
24
|
if (platform === 'linux') {
|
|
25
25
|
const name = 'simy-delivery-supervisor.service';
|
|
26
26
|
return { name, file: join(home, '.config/systemd/user', name),
|
|
27
|
-
content: `# ${marker}\n[Unit]\nDescription=SIMY Delivery supervisor recovery\n\n[Service]\nType=simple\nExecStart=${[node, ...args].map(systemdArgument).join(' ')}\nRestart=
|
|
27
|
+
content: `# ${marker}\n[Unit]\nDescription=SIMY Delivery supervisor recovery\n\n[Service]\nType=simple\nExecStart=${[node, ...args].map(systemdArgument).join(' ')}\nRestart=always\nRestartSec=15\nKillMode=process\n\n[Install]\nWantedBy=default.target\n` };
|
|
28
28
|
}
|
|
29
29
|
if (platform === 'darwin') {
|
|
30
30
|
const name = 'com.awak.simy.delivery-supervisor';
|
|
31
31
|
return { name, file: join(home, 'Library/LaunchAgents', `${name}.plist`), content:
|
|
32
|
-
`<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><!-- ${marker} --><dict><key>Label</key><string>${name}</string><key>ProgramArguments</key><array>${[node, ...args].map(arg => `<string>${xml(arg)}</string>`).join('')}</array><key>RunAtLoad</key><true/><key>KeepAlive</key><
|
|
32
|
+
`<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><!-- ${marker} --><dict><key>Label</key><string>${name}</string><key>ProgramArguments</key><array>${[node, ...args].map(arg => `<string>${xml(arg)}</string>`).join('')}</array><key>RunAtLoad</key><true/><key>KeepAlive</key><true/><key>ThrottleInterval</key><integer>15</integer></dict></plist>` };
|
|
33
33
|
}
|
|
34
34
|
if (platform === 'win32') {
|
|
35
35
|
const name = 'SIMYDeliverySupervisor';
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { supervisorTarget } from './supervisor-activation.js';
|
|
1
2
|
import { spawn } from 'node:child_process';
|
|
2
3
|
import { join } from 'node:path';
|
|
3
4
|
import { randomUUID } from 'node:crypto';
|
|
@@ -19,7 +20,9 @@ async function verifiedPin(root) {
|
|
|
19
20
|
return { digest: pin.digest, release: pin.release };
|
|
20
21
|
}
|
|
21
22
|
export async function setSupervisorWatchdog({ root, enabled, webOrigin,
|
|
22
|
-
inspectPin = verifiedPin, now = Date.now(), expectedEpoch } = {}) {
|
|
23
|
+
inspectPin = verifiedPin, now = Date.now(), expectedEpoch, target } = {}) {
|
|
24
|
+
if (target && !enabled) throw new Error('A recovery target requires explicit enable.');
|
|
25
|
+
const binding = target ? await supervisorTarget(root, target) : null;
|
|
23
26
|
const pin = enabled ? await inspectPin(root) : null;
|
|
24
27
|
const lock = await acquireDesktopProcessLock(join(folder(root), 'control-lock'), {
|
|
25
28
|
alive: supervisorProcessAlive, identity: supervisorProcessIdentity });
|
|
@@ -27,6 +30,8 @@ export async function setSupervisorWatchdog({ root, enabled, webOrigin,
|
|
|
27
30
|
const previous = await readSupervisorState(controlPath(root));
|
|
28
31
|
if (expectedEpoch !== undefined && previous?.epoch !== expectedEpoch) return previous;
|
|
29
32
|
const control = { version: 1, enabled: enabled === true, epoch: randomUUID(), updatedAt: now,
|
|
33
|
+
selection: { source: 'explicit_command', action: enabled ? 'enable' : 'disable', at: now },
|
|
34
|
+
...(binding ? { targets: [binding] } : {}),
|
|
30
35
|
...(pin ? { ...pin, webOrigin: resolveWebOrigin(webOrigin) } : {}) };
|
|
31
36
|
await saveSupervisorState(controlPath(root), control);
|
|
32
37
|
return control;
|
|
@@ -49,9 +54,11 @@ export function createSupervisorWatchdog({ root, inspectPin = verifiedPin, readC
|
|
|
49
54
|
if (closed) return;
|
|
50
55
|
const at = clock(), control = await readControl();
|
|
51
56
|
controlEpoch = control?.epoch;
|
|
57
|
+
const wake = lastWall !== null && (at < lastWall || at - lastWall > 60_000);
|
|
58
|
+
lastWall = at;
|
|
52
59
|
const previous = pendingPin || await readSupervisorState(statePath(root));
|
|
53
60
|
const state = { version: 1, handoverVersion: 1, watcherNonce, at, action: 'observe', supervisor: null, lastExit,
|
|
54
|
-
lastLaunchAt: launchTime ?? previous?.lastLaunchAt ?? null, epoch: control?.epoch || null };
|
|
61
|
+
lastLaunchAt: launchTime ?? previous?.lastLaunchAt ?? null, epoch: control?.epoch || null, lifecycle: wake ? 'wake' : 'observe' };
|
|
55
62
|
if (!control || control.version !== 1 || control.enabled !== true) { state.action = 'disabled'; await save(state); return state; }
|
|
56
63
|
state.supervisor = await observeOwner(root, { now: at });
|
|
57
64
|
if (state.supervisor.state === 'running') {
|
|
@@ -77,10 +84,8 @@ export function createSupervisorWatchdog({ root, inspectPin = verifiedPin, readC
|
|
|
77
84
|
}
|
|
78
85
|
// Resume/sleep or clock regression is an observation boundary, never proof
|
|
79
86
|
// that a live provider stopped. Re-observe on the next tick first.
|
|
80
|
-
if (
|
|
81
|
-
lastWall = at; state.action = 'wake_reobserve'; await save(state); return state;
|
|
87
|
+
if (wake) { state.action = 'wake_reobserve'; await save(state); return state;
|
|
82
88
|
}
|
|
83
|
-
lastWall = at;
|
|
84
89
|
try { await checkDesktop(root, null); }
|
|
85
90
|
catch (error) {
|
|
86
91
|
if (error.code !== 'process_conflict') throw error;
|
|
@@ -102,7 +107,7 @@ export function createSupervisorWatchdog({ root, inspectPin = verifiedPin, readC
|
|
|
102
107
|
!finalControl?.enabled || finalControl.epoch !== control.epoch) {
|
|
103
108
|
state.action = 'launch_cancelled'; await save(state); return state;
|
|
104
109
|
}
|
|
105
|
-
const args = [join(pin.release, 'src/index.js'), 'delivery', 'supervise', '--host', control.webOrigin, '--no-auto-update'];
|
|
110
|
+
const args = [join(pin.release, 'src/index.js'), 'delivery', 'supervise', '--activation-epoch', control.epoch, '--host', control.webOrigin, '--no-auto-update'];
|
|
106
111
|
child = launch(process.execPath, args, { env: { ...process.env, SIMY_HOME: root, SIMY_AUTO_UPDATE: '0' },
|
|
107
112
|
detached: process.platform !== 'win32', stdio: 'ignore', windowsHide: true });
|
|
108
113
|
const launched = child;
|
package/src/desktop-host.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { remoteOperationFailure } from './session-supervision/remote-errors.js';
|
|
1
2
|
import { createRemoteHostManager } from './session-supervision/remote-hosts.js';
|
|
2
3
|
import { readDesktopAutoUpdate, writeDesktopAutoUpdate } from './desktop-update-settings.js';
|
|
3
4
|
import { createUpdateRuntime } from './update-detachment/runtime.js';
|
|
@@ -25,7 +26,7 @@ import { controlDelivery, verifyDelivery, createRecordReader, updateRecord, reco
|
|
|
25
26
|
import { createManagedSupervisor } from "./delivery-hooks/supervisor.js";
|
|
26
27
|
import { createActionAssociationHost } from "./session-supervision/action-association-host.js";
|
|
27
28
|
import { createStopNotifier } from "./session-supervision/stop-notifications.js";
|
|
28
|
-
import { AutoContinueUnavailableError, answerSession, continueSession, resumeSession, discoverSessions, enrollSession, monitorSession, trackSession, setSessionAutoContinue } from "./session-supervision/index.js";
|
|
29
|
+
import { AutoContinueUnavailableError, answerSession, continueSession, followupSession, resumeSession, discoverSessions, enrollSession, monitorSession, trackSession, setSessionAutoContinue } from "./session-supervision/index.js";
|
|
29
30
|
import { createContinuationAnalysisManager } from "./session-supervision/analysis-manager.js";
|
|
30
31
|
import { analyzeContinuation, readContinuationContext } from "./session-supervision/continuation-analysis.js";
|
|
31
32
|
import { continueAnalyzedSession, createAutomaticContinuation } from "./session-supervision/automatic-continuation.js";
|
|
@@ -177,8 +178,8 @@ export async function startDesktopHost({ input = process.stdin, output = process
|
|
|
177
178
|
auto_update_busy: updateSettings.auto_update_busy === true } };
|
|
178
179
|
if (env.SIMY_REMOTE_CHILD === "1") status = { ...status, remoteSessionProtocol: 1 };
|
|
179
180
|
if (remoteHosts) {
|
|
180
|
-
void remoteHosts.update(providerLinks.
|
|
181
|
-
if (providerLinks.
|
|
181
|
+
void remoteHosts.update(PROVIDER_LINKS.some(provider => providerLinks[provider].connected) ? status : { ...status, access: { state: "unavailable" } }).catch(() => {});
|
|
182
|
+
if (PROVIDER_LINKS.some(provider => providerLinks[provider].connected)) status = remoteHosts.project(status, { providerLinks });
|
|
182
183
|
}
|
|
183
184
|
if (updateProgress) status = { ...status, update: { ...status.update, ...updateProgress } };
|
|
184
185
|
const { sampledAt, ...content } = status;
|
|
@@ -1167,7 +1168,7 @@ export async function startDesktopHost({ input = process.stdin, output = process
|
|
|
1167
1168
|
commandProviderLink = await requireProviderLink({ root: deliveryRoot, provider: command.provider });
|
|
1168
1169
|
}
|
|
1169
1170
|
if (command.hostId && command.hostId !== 'local') {
|
|
1170
|
-
if (!remoteHosts || command.provider
|
|
1171
|
+
if (!remoteHosts || !PROVIDER_LINKS.includes(command.provider)) throw Object.assign(new Error('Remote host is unavailable.'), { code: 'remote_host_unavailable' });
|
|
1171
1172
|
await authorizeProvider(command.provider, commandScope, commandProviderLink?.epoch);
|
|
1172
1173
|
const status = await agent.getDesktopStatus();
|
|
1173
1174
|
// Status collection can yield while provider consent is revoked.
|
|
@@ -1529,6 +1530,19 @@ export async function startDesktopHost({ input = process.stdin, output = process
|
|
|
1529
1530
|
await (dependencies.monitorSession || monitorSession)({ root: join(root, "delivery-hooks"), provider: command.provider,
|
|
1530
1531
|
session: command.session, monitor: action === "session_monitor", expectedProviderEpoch: commandProviderLink?.epoch });
|
|
1531
1532
|
await refreshSessions(true);
|
|
1533
|
+
} else if (action === "session_followup") {
|
|
1534
|
+
const candidate = await selectedSession(command);
|
|
1535
|
+
if (!candidate.followup?.previousRunId || command.previousRunId !== candidate.followup.previousRunId) {
|
|
1536
|
+
throw new Error('The finished task changed. Refresh this conversation before starting its follow-up.');
|
|
1537
|
+
}
|
|
1538
|
+
if (typeof command.objective !== 'string' || !command.objective.trim() || command.objective.length > 4000) {
|
|
1539
|
+
throw new Error('Enter the current goal to continue.');
|
|
1540
|
+
}
|
|
1541
|
+
await authorizeProvider(candidate.provider, commandScope, selectedLinkEpochs.get(candidate));
|
|
1542
|
+
await (dependencies.followupSession || followupSession)({ root: join(root, 'delivery-hooks'),
|
|
1543
|
+
provider: command.provider, session: command.session, previousRunId: command.previousRunId,
|
|
1544
|
+
objective: command.objective, followupAutoContinue: true, expectedProviderEpoch: selectedLinkEpochs.get(candidate) });
|
|
1545
|
+
await refreshSessions(true);
|
|
1532
1546
|
} else if (action === "session_enroll") {
|
|
1533
1547
|
await (dependencies.enrollSession || enrollSession)({ root: join(root, "delivery-hooks"), provider: command.provider,
|
|
1534
1548
|
session: command.session, objective: command.objective, acceptanceCriteria: command.acceptanceCriteria,
|
|
@@ -1571,7 +1585,7 @@ export async function startDesktopHost({ input = process.stdin, output = process
|
|
|
1571
1585
|
providerLinkFeedback[provider] = { state: 'error', message: desktopActionError(command.action, error) };
|
|
1572
1586
|
}
|
|
1573
1587
|
}
|
|
1574
|
-
emit({ type: "result", id: command.id, ok: false, ...(error?.code === 'cancelled' || statisticsRequest?.controller.signal.aborted ? { code: 'cancelled' } : {}), message: ["update", "prepare_update_restart"].includes(command.action) && updateProgress ? updateProgress.message : desktopActionError(command.action, error) });
|
|
1588
|
+
emit({ type: "result", id: command.id, ok: false, ...(remoteOperationFailure(error?.code).code ? { code: error.code } : {}), ...(error?.code === 'cancelled' || statisticsRequest?.controller.signal.aborted ? { code: 'cancelled' } : {}), message: ["update", "prepare_update_restart"].includes(command.action) && updateProgress ? updateProgress.message : desktopActionError(command.action, error) });
|
|
1575
1589
|
} finally {
|
|
1576
1590
|
// Access rejection can happen before the shared reader is constructed.
|
|
1577
1591
|
if (statisticsRequest && !statisticsRequest.promise && activeStatisticsRead === statisticsRequest) {
|
package/src/index.js
CHANGED
|
@@ -149,7 +149,7 @@ async function runCommand(installMode) {
|
|
|
149
149
|
simy sqm lint Validate module reliability before publication
|
|
150
150
|
simy sqm replay Replay modules against labelled historical snapshots
|
|
151
151
|
simy update --check Check the installed and latest stable CLI versions
|
|
152
|
-
simy sessions Show local Codex conversations (--interactive for search/navigation)
|
|
152
|
+
simy sessions Show local and registered remote Codex/Claude conversations (--interactive for search/navigation)
|
|
153
153
|
simy update ${installMode === "macos_installer" ? "Show Apple Silicon update status and installer action" : "Install an eligible stable CLI update"}
|
|
154
154
|
|
|
155
155
|
Options:
|
|
@@ -160,17 +160,17 @@ async function inspectTranscript(root, projectName, fileName, observedAt, includ
|
|
|
160
160
|
finally { await handle?.close(); }
|
|
161
161
|
}
|
|
162
162
|
|
|
163
|
-
async function collect({ home = homedir(), limit = 100, session = null, prioritySessions = [], includeContext = false, cacheMetadata = false, includeStatistics = false, includeBoundary = false, signal } = {}) {
|
|
163
|
+
async function collect({ home = homedir(), all = false, limit = 100, session = null, prioritySessions = [], includeContext = false, cacheMetadata = false, includeStatistics = false, includeBoundary = false, signal } = {}) {
|
|
164
164
|
if (signal?.aborted) return [];
|
|
165
165
|
const root = await projectsRoot(home);
|
|
166
166
|
if (!root) return [];
|
|
167
|
-
const maximum = Number.isInteger(limit) ? Math.max(1, Math.min(limit, RECENT_SESSION_LIMIT)) : 100;
|
|
167
|
+
const maximum = all ? Infinity : Number.isInteger(limit) ? Math.max(1, Math.min(limit, RECENT_SESSION_LIMIT)) : 100;
|
|
168
168
|
const observedAt = Date.now();
|
|
169
169
|
const result = new Map();
|
|
170
170
|
const descriptors = [], priorities = new Set(prioritySessions);
|
|
171
171
|
let projects;
|
|
172
172
|
try { projects = await readdir(root, { withFileTypes: true }); } catch { return []; }
|
|
173
|
-
for (const entry of projects.filter(item => item.isDirectory() && !item.isSymbolicLink()).slice(0, MAX_PROJECTS)) {
|
|
173
|
+
for (const entry of projects.filter(item => item.isDirectory() && !item.isSymbolicLink()).slice(0, all || session ? undefined : MAX_PROJECTS)) {
|
|
174
174
|
if (signal?.aborted) return [];
|
|
175
175
|
const project = join(root, entry.name);
|
|
176
176
|
let files;
|
|
@@ -203,11 +203,11 @@ async function collect({ home = homedir(), limit = 100, session = null, priority
|
|
|
203
203
|
...(!candidate.parentSession && origin.parentSession ? { parentSession: origin.parentSession, parentSessionSource: origin.source } : {}) };
|
|
204
204
|
return candidate;
|
|
205
205
|
};
|
|
206
|
-
const selected = session ? descriptors : [
|
|
206
|
+
const selected = session || all ? descriptors : [
|
|
207
207
|
...recentSessionWindow(descriptors.filter(item => desktopLineage.get(item.session)?.providerArchived !== true), { limit: maximum, priority: item => priorities.has(item.session) }),
|
|
208
208
|
...recentSessionWindow(descriptors.filter(item => desktopLineage.get(item.session)?.providerArchived === true), { limit: maximum, priority: item => priorities.has(item.session) }),
|
|
209
209
|
];
|
|
210
|
-
const filesToInspect = selected.slice(0, MAX_TRANSCRIPTS);
|
|
210
|
+
const filesToInspect = all ? selected : selected.slice(0, MAX_TRANSCRIPTS);
|
|
211
211
|
let nextFile = 0;
|
|
212
212
|
// Catalog prefixes are bounded independently of full transcript size. Use a
|
|
213
213
|
// small I/O pool; exact-context/statistics reads stay serial and identity-safe.
|
|
@@ -259,8 +259,8 @@ async function collect({ home = homedir(), limit = 100, session = null, priority
|
|
|
259
259
|
];
|
|
260
260
|
}
|
|
261
261
|
|
|
262
|
-
export async function listClaudeSessions({ home, limit, prioritySessions, signal } = {}) {
|
|
263
|
-
return collect({ home, limit, prioritySessions, signal, cacheMetadata: true });
|
|
262
|
+
export async function listClaudeSessions({ home, all = false, limit, prioritySessions, signal } = {}) {
|
|
263
|
+
return collect({ home, all, limit, prioritySessions, signal, cacheMetadata: true });
|
|
264
264
|
}
|
|
265
265
|
|
|
266
266
|
export async function readClaudeSession(session, { home } = {}) {
|
|
@@ -16,7 +16,7 @@ import { workspaceIdentity, verificationInstruction, normalizeVerification, asse
|
|
|
16
16
|
import { effectiveAcceptanceCriteria } from '../codex-plugins/simy/hooks/acceptance-policy.mjs';
|
|
17
17
|
import { buildPurposeInstruction } from './purpose-instruction.js';
|
|
18
18
|
import { peerOpinionPrompt } from '../codex-plugins/simy/hooks/purpose-cycle.mjs';
|
|
19
|
-
import {
|
|
19
|
+
import { runCodexPeerOpinion } from './codex-peer-opinion.js';
|
|
20
20
|
import { associationContract } from '../codex-plugins/simy/hooks/action-association.mjs';
|
|
21
21
|
import { spawn } from 'node:child_process';
|
|
22
22
|
import { realpath, stat, open } from 'node:fs/promises';
|
|
@@ -235,11 +235,13 @@ export function codexThreadMetadata(thread) {
|
|
|
235
235
|
};
|
|
236
236
|
}
|
|
237
237
|
|
|
238
|
-
export async function listCodexSessions({ client, maxPages = 40, pageSize = 25, maxSessions = RECENT_SESSION_LIMIT, archived = false, inspectState = false, prioritySessions = [], observationBudgetMs = 3000, codexHome } = {}) {
|
|
238
|
+
export async function listCodexSessions({ client, all = false, signal, maxPages = 40, pageSize = 25, maxSessions = RECENT_SESSION_LIMIT, archived = false, inspectState = false, prioritySessions = [], observationBudgetMs = 3000, codexHome } = {}) {
|
|
239
239
|
const sessions = [];
|
|
240
|
-
const windowSize = Math.min(maxSessions, maxPages * pageSize);
|
|
240
|
+
const windowSize = all ? Infinity : Math.min(maxSessions, maxPages * pageSize);
|
|
241
|
+
const cursors = new Set(), ids = new Set();
|
|
241
242
|
let cursor = null, listed = 0, pages = 0, batchSize = pageSize;
|
|
242
243
|
while (pages < Math.max(maxPages, Math.ceil(windowSize / batchSize)) && listed < windowSize) {
|
|
244
|
+
signal?.throwIfAborted();
|
|
243
245
|
const limit = Math.min(batchSize, windowSize - listed);
|
|
244
246
|
let response;
|
|
245
247
|
try { response = await client.request('thread/list', { cursor, limit, sourceKinds: SOURCE_KINDS,
|
|
@@ -251,14 +253,21 @@ export async function listCodexSessions({ client, maxPages = 40, pageSize = 25,
|
|
|
251
253
|
batchSize = Math.max(1, Math.floor(limit / 2));
|
|
252
254
|
continue;
|
|
253
255
|
}
|
|
254
|
-
|
|
256
|
+
if (!Array.isArray(response?.data) || response.data.length > limit)
|
|
257
|
+
throw new CodexAppServerError('invalid_page', 'Codex returned an invalid conversation page.');
|
|
258
|
+
const threads = response.data;
|
|
255
259
|
listed += threads.length; pages++;
|
|
256
260
|
for (const thread of threads) {
|
|
257
261
|
const metadata = codexThreadMetadata(thread);
|
|
258
|
-
if (metadata && SOURCE_KINDS.includes(metadata.source)
|
|
262
|
+
if (metadata && SOURCE_KINDS.includes(metadata.source) && !ids.has(metadata.session)) {
|
|
263
|
+
ids.add(metadata.session); sessions.push(metadata);
|
|
264
|
+
}
|
|
259
265
|
}
|
|
260
266
|
cursor = response?.nextCursor || null;
|
|
261
267
|
if (!cursor) break;
|
|
268
|
+
if (typeof cursor !== 'string' || cursors.has(cursor))
|
|
269
|
+
throw new CodexAppServerError('invalid_page', 'Codex repeated a conversation page cursor.');
|
|
270
|
+
cursors.add(cursor);
|
|
262
271
|
}
|
|
263
272
|
const deadline = Date.now() + Math.max(1, Math.min(observationBudgetMs, 5000));
|
|
264
273
|
// A recent page can omit an explicitly supervised conversation, including
|
|
@@ -645,7 +654,7 @@ async function frozenNativeSandbox(record, root, signal) {
|
|
|
645
654
|
return policy;
|
|
646
655
|
}
|
|
647
656
|
|
|
648
|
-
export async function executeCodexAppServer(record, { webOrigin, openClient = openCodexAppServer, signal, authorizePreparation = async () => {}, beforeDispatch = async () => {}, onStarted = async () => {}, onActivity = () => {}, onUsage = () => {}, onEvidence = async () => {}, observeExternal = collectPurposeObservations, root, auditOnly = false, opinionOnly = false, peerAction, runPeerReview =
|
|
657
|
+
export async function executeCodexAppServer(record, { webOrigin, openClient = openCodexAppServer, signal, authorizePreparation = async () => {}, beforeDispatch = async () => {}, onStarted = async () => {}, onActivity = () => {}, onUsage = () => {}, onEvidence = async () => {}, observeExternal = collectPurposeObservations, root, auditOnly = false, opinionOnly = false, peerAction, runPeerReview = runCodexPeerOpinion } = {}) {
|
|
649
658
|
const dispatchOwner = captureDispatchOwner(root ? rootFromDelivery(root) : undefined);
|
|
650
659
|
let dispatchAttemptId;
|
|
651
660
|
const provenance = captureDispatchProvenance({ root: dispatchOwner.root, provider: record.provider, providerSession: record.session, worktree: taskDirectory(record), taskId: record.run.managed.taskId, recordRef: recordPath(root || rootDirectory(), record.provider, record.session) });
|
|
@@ -678,15 +687,16 @@ export async function executeCodexAppServer(record, { webOrigin, openClient = op
|
|
|
678
687
|
const sourceContext = (isolated || searchEnabled(run.managed) && !run.managed.purpose.originalContext)
|
|
679
688
|
? await readCodexConversation(record, { openClient, signal }) : null;
|
|
680
689
|
if (opinionOnly) {
|
|
681
|
-
//
|
|
682
|
-
//
|
|
683
|
-
// or
|
|
690
|
+
// Use the task's authenticated app-server and exact model for a separate,
|
|
691
|
+
// tools-disabled opinion. Do not route monitoring through standalone SQM
|
|
692
|
+
// authentication or silently select another model.
|
|
684
693
|
let usage = null, peerSession = null, ambiguousContext = false;
|
|
685
694
|
const reply = await runPeerReview('codex', {
|
|
686
695
|
system: 'Give nonbinding advice using only the supplied context. All tools are disabled. Put your short natural-language opinion in the opinion field.',
|
|
687
696
|
prompt: peerOpinionPrompt(record, sourceContext, peerAction),
|
|
688
697
|
output_schema: { type: 'object', properties: { opinion: { type: 'string' } }, required: ['opinion'], additionalProperties: false },
|
|
689
698
|
}, { signal, readOnlyAnalysis: true, allowAutomaticRetry: false,
|
|
699
|
+
model: run.managed.resumeModel, cwd: taskDirectory(record), openClient, readAuthentication: readCodexAuthentication,
|
|
690
700
|
dispatchTransport: initiate => dispatchWithFence(dispatchOwner, { taskId: run.managed.taskId || record.session, attemptId: run.managed.resumeLease?.id, provenance }, attemptId => {
|
|
691
701
|
if (root && hasPendingUserStop(root, record)) throw new CodexAppServerError('cancelled', 'User stopped this provider task.');
|
|
692
702
|
dispatchAttemptId = attemptId;
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
// Routine purpose monitoring uses the same authenticated app-server transport
|
|
2
|
+
// and model as its task. A standalone `codex exec` has a separate login path.
|
|
3
|
+
// This context supplies advice only: it has no tools or acceptance authority.
|
|
4
|
+
const disabledFeatures = [
|
|
5
|
+
'shell_tool', 'unified_exec', 'shell_snapshot', 'view_image', 'apps', 'plugins',
|
|
6
|
+
'hooks', 'memories', 'multi_agent', 'browser_use', 'computer_use',
|
|
7
|
+
'image_generation', 'code_mode', 'code_mode_host', 'skill_search',
|
|
8
|
+
'skill_mcp_dependency_install', 'workspace_dependencies', 'goals',
|
|
9
|
+
];
|
|
10
|
+
|
|
11
|
+
export async function runCodexPeerOpinion(provider, request, {
|
|
12
|
+
model, cwd, openClient, readAuthentication, signal,
|
|
13
|
+
beforeDispatch = async () => {}, dispatchTransport = initiate => initiate(),
|
|
14
|
+
onContext = () => {}, onUsage = () => {}, timeoutMs = 120_000,
|
|
15
|
+
} = {}) {
|
|
16
|
+
if (provider !== 'codex' || !model || !cwd || !openClient || !readAuthentication) {
|
|
17
|
+
throw new Error('Peer opinion requires the task’s Codex transport, model and workspace.');
|
|
18
|
+
}
|
|
19
|
+
signal = AbortSignal.any([...(signal ? [signal] : []), AbortSignal.timeout(timeoutMs)]);
|
|
20
|
+
signal.throwIfAborted();
|
|
21
|
+
const client = await openClient({ signal, cancelOnAbort: true, isolateConnectors: true, maxLineBytes: 1024 * 1024 });
|
|
22
|
+
let threadId, turnId, completed = false, unsubscribe, abort, closed;
|
|
23
|
+
let startPromise;
|
|
24
|
+
try {
|
|
25
|
+
if (await readAuthentication(client) === 'missing') {
|
|
26
|
+
throw Object.assign(new Error('The task’s Codex account is not signed in.'), { code: 'authentication_required' });
|
|
27
|
+
}
|
|
28
|
+
const config = await client.request('config/read', { cwd, includeLayers: false });
|
|
29
|
+
if (!config?.config) throw new Error('Peer configuration is unavailable.');
|
|
30
|
+
const created = await client.request('thread/start', {
|
|
31
|
+
cwd, model, ephemeral: true, sandbox: 'read-only', approvalPolicy: 'never',
|
|
32
|
+
developerInstructions: request.system,
|
|
33
|
+
config: {
|
|
34
|
+
web_search: 'disabled',
|
|
35
|
+
features: {
|
|
36
|
+
...Object.fromEntries(disabledFeatures.map(name => [name, false])),
|
|
37
|
+
enable_fanout: false, multi_agent_v2: { enabled: false },
|
|
38
|
+
skip_host_skill_discovery: true,
|
|
39
|
+
},
|
|
40
|
+
mcp_servers: Object.fromEntries(Object.keys(config.config.mcp_servers || {}).map(name => [name, { enabled: false }])),
|
|
41
|
+
},
|
|
42
|
+
});
|
|
43
|
+
threadId = created.thread?.id;
|
|
44
|
+
if (!threadId || created.model !== model || created.cwd !== cwd ||
|
|
45
|
+
created.sandbox?.type !== 'readOnly' || created.approvalPolicy !== 'never') {
|
|
46
|
+
throw new Error('Peer context does not match the task’s isolated configuration.');
|
|
47
|
+
}
|
|
48
|
+
let cursor = null;
|
|
49
|
+
const cursors = new Set();
|
|
50
|
+
do {
|
|
51
|
+
const inventory = await client.request('mcpServerStatus/list', { threadId, cursor, limit: 1 });
|
|
52
|
+
if (!Array.isArray(inventory.data)) throw new Error('Peer connector inventory is unavailable.');
|
|
53
|
+
if (inventory.data?.some(server => server.toolsError || Object.keys(server.tools || {}).length ||
|
|
54
|
+
server.resources?.length || server.resourceTemplates?.length)) {
|
|
55
|
+
throw new Error('Peer context still has connector capabilities.');
|
|
56
|
+
}
|
|
57
|
+
cursor = inventory.nextCursor;
|
|
58
|
+
if (cursor && (cursors.has(cursor) || cursors.size >= 100)) throw new Error('Peer connector inventory is incomplete.');
|
|
59
|
+
if (cursor) cursors.add(cursor);
|
|
60
|
+
} while (cursor);
|
|
61
|
+
await onContext(threadId);
|
|
62
|
+
const messages = new Map(), turns = new Map(), usage = new Map();
|
|
63
|
+
let resolveDone, rejectDone, settled = false, lastUsage;
|
|
64
|
+
const done = new Promise((resolve, reject) => { resolveDone = resolve; rejectDone = reject; });
|
|
65
|
+
// Preparation/dispatch can fail before the completion promise is awaited.
|
|
66
|
+
done.catch(() => {});
|
|
67
|
+
const fail = error => { if (!settled) { settled = true; rejectDone(error); } };
|
|
68
|
+
const reportUsage = () => {
|
|
69
|
+
const observed = usage.get(turnId);
|
|
70
|
+
if (observed && observed !== lastUsage) {
|
|
71
|
+
lastUsage = observed;
|
|
72
|
+
try { onUsage(observed); } catch (error) { fail(error); }
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
const finish = () => {
|
|
76
|
+
if (settled || !turnId || !turns.has(turnId)) return;
|
|
77
|
+
const turn = turns.get(turnId);
|
|
78
|
+
completed = true;
|
|
79
|
+
if (turn.status !== 'completed') return fail(Object.assign(new Error('Peer turn did not complete.'), { code: 'turn_failed' }));
|
|
80
|
+
let output;
|
|
81
|
+
try { output = JSON.parse(messages.get(turnId) || ''); } catch {
|
|
82
|
+
return fail(new Error('Peer opinion did not return structured output.'));
|
|
83
|
+
}
|
|
84
|
+
if (typeof output.opinion !== 'string' || !output.opinion.trim()) return fail(new Error('Peer opinion was empty.'));
|
|
85
|
+
reportUsage();
|
|
86
|
+
if (settled) return;
|
|
87
|
+
settled = true;
|
|
88
|
+
resolveDone({ output: { opinion: output.opinion }, model });
|
|
89
|
+
};
|
|
90
|
+
unsubscribe = client.onNotification((method, params, requestId) => {
|
|
91
|
+
if (params.threadId !== threadId) return;
|
|
92
|
+
if (requestId !== undefined) return fail(Object.assign(new Error('Peer requested a tool or approval.'), { code: 'provider_approval' }));
|
|
93
|
+
if (method === 'item/completed' && params.item?.type === 'agentMessage') messages.set(params.turnId, params.item.text);
|
|
94
|
+
if (['item/started', 'item/completed'].includes(method) && ['commandExecution', 'mcpToolCall', 'fileChange', 'webSearch', 'dynamicToolCall'].includes(params.item?.type)) {
|
|
95
|
+
return fail(new Error('Peer attempted a disabled tool.'));
|
|
96
|
+
}
|
|
97
|
+
if (method === 'thread/tokenUsage/updated') {
|
|
98
|
+
const tokens = params.tokenUsage?.total?.totalTokens;
|
|
99
|
+
if (Number.isSafeInteger(tokens) && tokens >= 0) usage.set(params.turnId, { source: 'codex_app_server', tokens, observedAt: Date.now() });
|
|
100
|
+
reportUsage();
|
|
101
|
+
}
|
|
102
|
+
if (method === 'turn/completed' && params.turn?.id) turns.set(params.turn.id, params.turn);
|
|
103
|
+
finish();
|
|
104
|
+
});
|
|
105
|
+
abort = () => fail(Object.assign(new Error('Peer inspection cancelled.'), { code: 'cancelled' }));
|
|
106
|
+
closed = () => fail(Object.assign(new Error('Peer connection closed.'), { code: 'closed' }));
|
|
107
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
108
|
+
client.child?.once('close', closed);
|
|
109
|
+
await beforeDispatch();
|
|
110
|
+
signal?.throwIfAborted();
|
|
111
|
+
startPromise = Promise.resolve(dispatchTransport(() => client.request('turn/start', {
|
|
112
|
+
threadId, model, cwd, input: [{ type: 'text', text: request.prompt }],
|
|
113
|
+
outputSchema: request.output_schema, sandboxPolicy: { type: 'readOnly', networkAccess: false },
|
|
114
|
+
})));
|
|
115
|
+
const started = await Promise.race([startPromise, done]);
|
|
116
|
+
turnId = started.turn?.id;
|
|
117
|
+
if (!turnId) throw new Error('Peer turn did not start.');
|
|
118
|
+
reportUsage();
|
|
119
|
+
finish();
|
|
120
|
+
return await done;
|
|
121
|
+
} finally {
|
|
122
|
+
signal?.removeEventListener('abort', abort);
|
|
123
|
+
if (closed) client.child?.removeListener('close', closed);
|
|
124
|
+
unsubscribe?.();
|
|
125
|
+
if (!completed && turnId) await client.request('turn/interrupt', { threadId, turnId }, 2000).catch(() => {});
|
|
126
|
+
await client.close();
|
|
127
|
+
}
|
|
128
|
+
}
|