@nathanstephenson/flow 0.1.2 → 0.1.4
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 +46 -2
- package/build/workflow-runtime.cjs +1 -46
- package/dist/backend/claude/index.js +135 -39
- package/dist/backend/claude/mcp.js +3 -1
- package/dist/backend/claude/permissions.js +26 -15
- package/dist/backend/claude/subagents.js +4 -0
- package/dist/backend/claude/workflow-parent.js +4 -1
- package/dist/backend/claude/workflow-subagent.js +2 -2
- package/dist/backend/mcp-stdio-supervisor.js +196 -0
- package/dist/backend/mcp.js +146 -51
- package/dist/backend/permission-errors.js +3 -0
- package/dist/backend/pi/agent-permissions.js +74 -0
- package/dist/backend/pi/auto-compaction.js +1 -3
- package/dist/backend/pi/compaction-model.js +38 -0
- package/dist/backend/pi/index.js +71 -24
- package/dist/backend/pi/work.js +1 -1
- package/dist/backend/pi/workflow-subagent.js +11 -2
- package/dist/backend/registry.js +5 -30
- package/dist/backend/worker/assets.js +16 -0
- package/dist/backend/worker/claude-state.js +61 -0
- package/dist/backend/worker/entry.js +186 -0
- package/dist/backend/worker/index.js +255 -0
- package/dist/backend/worker/launcher.js +67 -0
- package/dist/backend/worker/protocol.js +11 -0
- package/dist/backend/worker/rpc.js +108 -0
- package/dist/build-id +1 -1
- package/dist/cli/bootstrap.js +1 -1
- package/dist/cli/main.js +9 -1
- package/dist/client/connection.js +107 -2
- package/dist/client/diff.js +43 -0
- package/dist/client/reduce.js +3 -0
- package/dist/daemon/config-store.js +38 -2
- package/dist/daemon/config.js +110 -51
- package/dist/daemon/host.js +301 -30
- package/dist/daemon/log.js +98 -0
- package/dist/daemon/runtime.js +10 -1
- package/dist/daemon/server.js +67 -1
- package/dist/daemon/workflow-execution-routes.js +1 -1
- package/dist/daemon/workflow-executions.js +72 -27
- package/dist/daemon/workflow-mcp.js +2 -4
- package/dist/daemon/workflow-routes.js +4 -3
- package/dist/isolation/filesystem.js +382 -0
- package/dist/isolation/launcher.js +40 -0
- package/dist/isolation/node-assets.js +84 -0
- package/dist/isolation/support.js +40 -0
- package/dist/isolation/toolchain-assets.js +62 -0
- package/dist/protocol/presentation.js +230 -0
- package/dist/protocol/settings.js +1 -4
- package/dist/workflows/executors.js +118 -62
- package/dist/workflows/graph.js +3 -6
- package/dist/workflows/json-schema.js +8 -3
- package/dist/workflows/mcp.js +15 -1
- package/dist/workflows/runtime-settings.js +7 -7
- package/dist/workflows/runtime.js +1 -34
- package/package.json +5 -4
- package/web/dist/assets/index-Bn-ECZ7w.js +174 -0
- package/web/dist/assets/index-DL0CGVaN.css +2 -0
- package/web/dist/assets/input-NIrLDFaS.js +6 -0
- package/web/dist/assets/settings-mcp-B60T2XUv.js +1 -0
- package/web/dist/assets/settings-secrets-BtQwc-w4.js +1 -0
- package/web/dist/assets/settings-workflows-BZ4W0Ja8.js +23 -0
- package/web/dist/assets/switch-DyYU6B5T.js +1 -0
- package/web/dist/assets/workflows-BAdf2yKH.js +7 -0
- package/web/dist/assets/workflows-pane-MSSNIrgu.js +1 -0
- package/web/dist/index.html +4 -4
- package/web/dist/assets/index-BlZBshi8.js +0 -170
- package/web/dist/assets/index-DWF4-3Fh.css +0 -2
- package/web/dist/assets/select-6i3wxovH.js +0 -1
- package/web/dist/assets/settings-mcp-ZMIfuuZU.js +0 -1
- package/web/dist/assets/settings-secrets-CgTrBpi2.js +0 -1
- package/web/dist/assets/settings-workflows-1DMYfZtn.js +0 -23
- package/web/dist/assets/switch-ftZleVB8.js +0 -6
- package/web/dist/assets/workflows-CBuB_bva.js +0 -7
- package/web/dist/assets/workflows-pane-DPXGg0na.js +0 -1
package/dist/daemon/host.js
CHANGED
|
@@ -202,14 +202,19 @@ export class SessionHost {
|
|
|
202
202
|
defaultBackend;
|
|
203
203
|
defaultModel;
|
|
204
204
|
autoCompaction;
|
|
205
|
+
compactionModel;
|
|
205
206
|
defaultEffort;
|
|
207
|
+
defaultPermissionMode;
|
|
206
208
|
summaryModel;
|
|
207
209
|
closedListeners = new Set();
|
|
210
|
+
backendFailures = new Set();
|
|
208
211
|
keptListeners = new Set();
|
|
212
|
+
filesystemIsolation;
|
|
209
213
|
mcpConnections;
|
|
210
214
|
mcpAuth;
|
|
211
215
|
resolveSecret;
|
|
212
216
|
constructor(options = {}) {
|
|
217
|
+
this.filesystemIsolation = options.filesystemIsolationEnabled;
|
|
213
218
|
this.mcpConnections = options.mcpConnections;
|
|
214
219
|
this.mcpAuth = options.mcpAuth;
|
|
215
220
|
this.resolveSecret = options.resolveSecret;
|
|
@@ -220,7 +225,9 @@ export class SessionHost {
|
|
|
220
225
|
this.defaultBackend = options.defaultBackend;
|
|
221
226
|
this.defaultModel = options.defaultModel;
|
|
222
227
|
this.autoCompaction = options.autoCompaction;
|
|
228
|
+
this.compactionModel = options.compactionModel;
|
|
223
229
|
this.defaultEffort = options.defaultEffort;
|
|
230
|
+
this.defaultPermissionMode = options.defaultPermissionMode;
|
|
224
231
|
this.summaryModel = options.summaryModel;
|
|
225
232
|
}
|
|
226
233
|
/**
|
|
@@ -409,6 +416,7 @@ export class SessionHost {
|
|
|
409
416
|
scope: record.scope,
|
|
410
417
|
backend: record.backendName,
|
|
411
418
|
status,
|
|
419
|
+
permissionMode: record.permissionMode,
|
|
412
420
|
title: record.title,
|
|
413
421
|
...(record.outputPreview === undefined ? {} : { outputPreview: record.outputPreview }),
|
|
414
422
|
restingAt: record.restingAt,
|
|
@@ -497,6 +505,7 @@ export class SessionHost {
|
|
|
497
505
|
resumeToken: meta.resumeToken,
|
|
498
506
|
modelId: meta.modelId,
|
|
499
507
|
effort: meta.effort,
|
|
508
|
+
permissionMode: meta.permissionMode ?? this.permissionDefault(meta.backend),
|
|
500
509
|
initialEffortUnconfirmed: meta.initialEffortUnconfirmed ?? false,
|
|
501
510
|
createdAt: meta.createdAt,
|
|
502
511
|
updatedAt: meta.updatedAt,
|
|
@@ -505,6 +514,8 @@ export class SessionHost {
|
|
|
505
514
|
// Empties all three sets seeded above: a torn turn's prompts and Subagents are closed here,
|
|
506
515
|
// and nothing can be open on an Agent Session with no Backend Session attached.
|
|
507
516
|
this.closeTornTurn(record, entries);
|
|
517
|
+
if (!meta.permissionMode)
|
|
518
|
+
record.log.append({ type: "permission_mode_changed", mode: record.permissionMode });
|
|
508
519
|
// Dormancy has to be visible to a client reducing the transcript, or a session with nothing
|
|
509
520
|
// running still looks ready to type at. A clean shutdown already recorded it.
|
|
510
521
|
if (record.lifecycle === "dormant" && lastEventType(record.log.since(0)) !== "session_dormant") {
|
|
@@ -523,11 +534,14 @@ export class SessionHost {
|
|
|
523
534
|
if (backendName === undefined)
|
|
524
535
|
throw new Error("No backends available");
|
|
525
536
|
const backend = this.backendFor(backendName);
|
|
537
|
+
// Reject an unsupported policy before creating a worktree or any durable Agent Session state.
|
|
538
|
+
const permissionMode = options.permissionMode ?? this.permissionDefault(backend.name);
|
|
539
|
+
this.validatePermissionMode(backend.name, permissionMode);
|
|
526
540
|
const worktree = options.worktree ? await this.cutWorktree(options.scope, options.worktree) : undefined;
|
|
527
541
|
// The Scope from here down, and for this Agent Session's whole life. Resolved before any record
|
|
528
542
|
// exists so that a `worktree add` which failed leaves nothing persisted pointing at a directory
|
|
529
543
|
// that is not there.
|
|
530
|
-
const scope = worktree?.path ?? options.scope;
|
|
544
|
+
const scope = scopeKey(worktree?.path ?? options.scope);
|
|
531
545
|
const id = randomUUID();
|
|
532
546
|
const now = new Date().toISOString();
|
|
533
547
|
const modelId = options.modelId ?? this.defaultModel?.(backend.name);
|
|
@@ -579,6 +593,7 @@ export class SessionHost {
|
|
|
579
593
|
*/
|
|
580
594
|
modelId,
|
|
581
595
|
effort,
|
|
596
|
+
permissionMode,
|
|
582
597
|
initialEffortUnconfirmed: effort !== undefined,
|
|
583
598
|
createdAt: now,
|
|
584
599
|
updatedAt: now,
|
|
@@ -586,12 +601,29 @@ export class SessionHost {
|
|
|
586
601
|
this.sessions.set(id, record);
|
|
587
602
|
this.persist(record);
|
|
588
603
|
record.buffered = [];
|
|
589
|
-
|
|
604
|
+
let session;
|
|
605
|
+
try {
|
|
606
|
+
session = await this.startPermissionBackend(record);
|
|
607
|
+
if (session.capabilities.models.length === 0) {
|
|
608
|
+
throw new CommandRefused("Model capabilities are unavailable. Check the backend and try again.");
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
catch (error) {
|
|
612
|
+
// Creation never returns an Agent Session without confirmed models. In particular, do not
|
|
613
|
+
// leave a persisted, empty Agent Session (or a newly cut worktree) after a failed probe.
|
|
614
|
+
await record.session?.dispose().catch(() => { });
|
|
615
|
+
await this.releaseWorktree(record);
|
|
616
|
+
record.log.closeSubscribers();
|
|
617
|
+
this.sessions.delete(id);
|
|
618
|
+
this.store?.deleteSession(id);
|
|
619
|
+
throw error;
|
|
620
|
+
}
|
|
590
621
|
record.log.append({
|
|
591
622
|
type: "session_started",
|
|
592
623
|
backend: backend.name,
|
|
593
624
|
scope,
|
|
594
625
|
capabilities: session.capabilities,
|
|
626
|
+
permissionMode: record.permissionMode,
|
|
595
627
|
...(worktree === undefined ? {} : { worktree: true }),
|
|
596
628
|
});
|
|
597
629
|
this.flushBuffered(record);
|
|
@@ -678,6 +710,11 @@ export class SessionHost {
|
|
|
678
710
|
throw new Error(`Session ${sessionId} has ended`);
|
|
679
711
|
if (record.reviving)
|
|
680
712
|
return await record.reviving;
|
|
713
|
+
if (record.permissionChanging) {
|
|
714
|
+
await this.waitForPermissionChange(record);
|
|
715
|
+
// Another caller may have Revived or Ended it while the policy transition was in flight.
|
|
716
|
+
return await this.revive(sessionId);
|
|
717
|
+
}
|
|
681
718
|
const reviving = this.reviveOnce(record);
|
|
682
719
|
record.reviving = reviving;
|
|
683
720
|
try {
|
|
@@ -698,7 +735,7 @@ export class SessionHost {
|
|
|
698
735
|
this.closeOpenSubagents(record, record.log.since(0));
|
|
699
736
|
this.closeOpenBackgroundCalls(record, record.log.since(0));
|
|
700
737
|
record.backendEpoch += 1;
|
|
701
|
-
await this.
|
|
738
|
+
await this.startPermissionBackend(record);
|
|
702
739
|
record.lifecycle = "live";
|
|
703
740
|
// Un-settled, so the retention window starts again from the next Settle rather than from the
|
|
704
741
|
// one this Revive just undid.
|
|
@@ -724,6 +761,8 @@ export class SessionHost {
|
|
|
724
761
|
// ADR 0003: the first message revives a Dormant session, so resuming work is one action.
|
|
725
762
|
if (!record.session)
|
|
726
763
|
await this.revive(sessionId);
|
|
764
|
+
if (record.permissionChanging)
|
|
765
|
+
await this.waitForPermissionChange(record);
|
|
727
766
|
// Checked before anything is written, so a refused send leaves no bytes behind.
|
|
728
767
|
this.refuseUnservableAttachments(record, attachments);
|
|
729
768
|
const ids = (attachments ?? []).map((attachment) => this.storeOrThrow().writeAttachment(record.id, attachment.mediaType, attachment.data));
|
|
@@ -733,13 +772,7 @@ export class SessionHost {
|
|
|
733
772
|
this.touch(record);
|
|
734
773
|
return;
|
|
735
774
|
}
|
|
736
|
-
|
|
737
|
-
await this.dispatch(record, { text, attachments: ids });
|
|
738
|
-
}
|
|
739
|
-
catch (error) {
|
|
740
|
-
this.recordDispatchFailure(record, error);
|
|
741
|
-
throw error;
|
|
742
|
-
}
|
|
775
|
+
await this.dispatch(record, { text, attachments: ids });
|
|
743
776
|
}
|
|
744
777
|
/**
|
|
745
778
|
* Whether this send's Attachments can be carried at all, refused before any are written down.
|
|
@@ -817,6 +850,116 @@ export class SessionHost {
|
|
|
817
850
|
record.initialEffortUnconfirmed = false;
|
|
818
851
|
this.touch(record);
|
|
819
852
|
}
|
|
853
|
+
permissionDefault(backend) {
|
|
854
|
+
return this.defaultPermissionMode?.(backend) ?? (backend === "claude" ? "auto" : backend === "pi" ? "always" : "ask");
|
|
855
|
+
}
|
|
856
|
+
validatePermissionMode(backend, mode) {
|
|
857
|
+
if (!["ask", "auto", "always"].includes(mode) || (mode === "auto" && backend !== "claude"))
|
|
858
|
+
throw new CommandRefused(`${backend} does not support ${mode} permissions`);
|
|
859
|
+
}
|
|
860
|
+
async waitForPermissionChange(record) {
|
|
861
|
+
// A failed selection leaves the last confirmed mode in force; it must not discard a send.
|
|
862
|
+
while (record.permissionChanging)
|
|
863
|
+
await record.permissionChanging.catch(() => { });
|
|
864
|
+
}
|
|
865
|
+
async setPermissionMode(sessionId, mode) {
|
|
866
|
+
const record = this.record(sessionId);
|
|
867
|
+
this.validatePermissionMode(record.backendName, mode);
|
|
868
|
+
const previous = record.permissionChanging;
|
|
869
|
+
const reviving = record.reviving;
|
|
870
|
+
// Reserve before yielding, including for a Dormant Agent Session. Capture the existing Revive
|
|
871
|
+
// rather than reading it later: a new Revive waits for this reservation, not vice versa.
|
|
872
|
+
const changing = Promise.resolve().then(async () => {
|
|
873
|
+
await previous?.catch(() => { });
|
|
874
|
+
await reviving;
|
|
875
|
+
await this.setPermissionModeOnce(record, mode);
|
|
876
|
+
});
|
|
877
|
+
record.permissionChanging = changing;
|
|
878
|
+
try {
|
|
879
|
+
await changing;
|
|
880
|
+
}
|
|
881
|
+
finally {
|
|
882
|
+
if (record.permissionChanging === changing) {
|
|
883
|
+
delete record.permissionChanging;
|
|
884
|
+
if (record.session && record.lifecycle === "live" && !record.turnInFlight)
|
|
885
|
+
void this.drain(record);
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
async setPermissionModeOnce(record, mode) {
|
|
890
|
+
if (record.lifecycle === "ended" || record.turnInFlight || record.openPermissionAttention.size ||
|
|
891
|
+
openPermissions(record.log.since(0)).length)
|
|
892
|
+
throw new CommandRefused("Finish the turn and decide all Permission Prompts first");
|
|
893
|
+
if (record.permissionMode === mode)
|
|
894
|
+
return;
|
|
895
|
+
const session = record.session;
|
|
896
|
+
const priorMode = record.permissionMode;
|
|
897
|
+
const activityVersion = record.permissionActivityVersion ?? 0;
|
|
898
|
+
let interrupted = false;
|
|
899
|
+
const apply = async (next) => {
|
|
900
|
+
try {
|
|
901
|
+
await session?.setPermissionMode?.(next);
|
|
902
|
+
}
|
|
903
|
+
finally {
|
|
904
|
+
// The host reservation cannot stop an SDK-owned background completion or Subagent prompt.
|
|
905
|
+
// Do not confirm a policy that raced either, even if that work already ended again.
|
|
906
|
+
interrupted = record.session !== session || record.lifecycle === "ended" || record.turnInFlight ||
|
|
907
|
+
record.openPermissionAttention.size > 0 || (record.permissionActivityVersion ?? 0) !== activityVersion;
|
|
908
|
+
if (interrupted) {
|
|
909
|
+
if (session && record.session === session) {
|
|
910
|
+
try {
|
|
911
|
+
await session.setPermissionMode?.(priorMode);
|
|
912
|
+
}
|
|
913
|
+
catch (error) {
|
|
914
|
+
await this.stopUnconfirmedPermissionBackend(record, session, error);
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
throw new CommandRefused("Permission mode change interrupted by Backend Session activity; try again when idle");
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
};
|
|
921
|
+
let warning;
|
|
922
|
+
// No optimistic event: a failed SDK transition must not change either client or disk.
|
|
923
|
+
try {
|
|
924
|
+
await apply(mode);
|
|
925
|
+
}
|
|
926
|
+
catch (error) {
|
|
927
|
+
if (interrupted || mode !== "auto" || record.backendName !== "claude")
|
|
928
|
+
throw error;
|
|
929
|
+
await apply("ask");
|
|
930
|
+
mode = "ask";
|
|
931
|
+
warning = `Claude Auto permissions unavailable: ${String(error)}. Using Ask.`;
|
|
932
|
+
}
|
|
933
|
+
record.permissionMode = mode;
|
|
934
|
+
if (warning)
|
|
935
|
+
record.log.append({ type: "notice", level: "warn", text: warning });
|
|
936
|
+
record.log.append({ type: "permission_mode_changed", mode });
|
|
937
|
+
this.touch(record);
|
|
938
|
+
}
|
|
939
|
+
async stopUnconfirmedPermissionBackend(record, session, error) {
|
|
940
|
+
// Rollback itself awaited the SDK: do not stop a replacement, or revive an Ended/Settled record.
|
|
941
|
+
if (record.session !== session)
|
|
942
|
+
return;
|
|
943
|
+
// A rejected rollback leaves SDK policy unknown. Stop rather than display the old confirmed
|
|
944
|
+
// mode over a backend that may still be executing under the unconfirmed one.
|
|
945
|
+
record.session = undefined;
|
|
946
|
+
record.lifecycle = "dormant";
|
|
947
|
+
record.turnInFlight = false;
|
|
948
|
+
record.queue.length = 0;
|
|
949
|
+
try {
|
|
950
|
+
await this.stopBackendSession(record.scope, session, record.id);
|
|
951
|
+
}
|
|
952
|
+
finally {
|
|
953
|
+
// An explicit End/Settle while shutdown awaited must remain the final lifecycle transition.
|
|
954
|
+
if (record.lifecycle === "dormant" && record.session === undefined) {
|
|
955
|
+
this.closeTornTurn(record, record.log.since(0));
|
|
956
|
+
record.log.append({ type: "queue_changed", pending: [] });
|
|
957
|
+
record.log.append({ type: "notice", level: "error", text: `Could not restore permission mode; Backend Session stopped: ${errorMessage(error)}` });
|
|
958
|
+
record.log.append({ type: "session_dormant", reason: "permission mode could not be confirmed" });
|
|
959
|
+
this.touch(record);
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
}
|
|
820
963
|
async setEffort(sessionId, effort) {
|
|
821
964
|
const record = this.record(sessionId);
|
|
822
965
|
await record.session?.setEffort(effort);
|
|
@@ -989,6 +1132,8 @@ export class SessionHost {
|
|
|
989
1132
|
}
|
|
990
1133
|
if (!record.session)
|
|
991
1134
|
await this.revive(sessionId);
|
|
1135
|
+
if (record.permissionChanging)
|
|
1136
|
+
await this.waitForPermissionChange(record);
|
|
992
1137
|
this.refuseGitOperation(record.scope);
|
|
993
1138
|
const session = record.session;
|
|
994
1139
|
if (!session) {
|
|
@@ -1211,7 +1356,7 @@ export class SessionHost {
|
|
|
1211
1356
|
* must not become "after every message that happened to be queued while it ran".
|
|
1212
1357
|
*/
|
|
1213
1358
|
async drainWorkflowNotification(record) {
|
|
1214
|
-
if (record.turnInFlight || !record.session || record.lifecycle !== 'live' || this.workflowShutdown || this.workflowStopping.has(record.id))
|
|
1359
|
+
if (record.permissionChanging || record.turnInFlight || !record.session || record.lifecycle !== 'live' || this.workflowShutdown || this.workflowStopping.has(record.id))
|
|
1215
1360
|
return false;
|
|
1216
1361
|
let kind;
|
|
1217
1362
|
let text;
|
|
@@ -1255,19 +1400,23 @@ export class SessionHost {
|
|
|
1255
1400
|
record.turnInFlight = false;
|
|
1256
1401
|
return false;
|
|
1257
1402
|
}
|
|
1403
|
+
const session = record.session;
|
|
1404
|
+
const generation = record.turnGeneration = (record.turnGeneration ?? 0) + 1;
|
|
1405
|
+
const failed = (error) => {
|
|
1406
|
+
if (record.lifecycle !== 'live' || record.session !== session || record.turnGeneration !== generation)
|
|
1407
|
+
return;
|
|
1408
|
+
if (kind === 'input')
|
|
1409
|
+
this.workflowOwner?.rearmInput?.(record.id);
|
|
1410
|
+
this.recordDispatchFailure(record, new Error(`Could not notify parent: ${errorMessage(error)}`));
|
|
1411
|
+
};
|
|
1258
1412
|
try {
|
|
1259
|
-
|
|
1260
|
-
return true;
|
|
1413
|
+
void session.prompt(text).catch(failed);
|
|
1261
1414
|
}
|
|
1262
1415
|
catch (error) {
|
|
1263
|
-
|
|
1264
|
-
if (kind === 'input')
|
|
1265
|
-
this.workflowOwner?.rearmInput?.(record.id);
|
|
1266
|
-
record.log.append({ type: 'notice', level: 'warn', text: `Could not notify parent: ${errorMessage(error)}` });
|
|
1267
|
-
// The notification was consumed but no turn began. Keep draining in case another workflow
|
|
1268
|
-
// event is ready; returning false when there is not one lets drain() release the Steering Queue.
|
|
1269
|
-
return this.drainWorkflowNotification(record);
|
|
1416
|
+
failed(error);
|
|
1270
1417
|
}
|
|
1418
|
+
// Consumed, not completed: turn events (or the guarded rejection) release subsequent work.
|
|
1419
|
+
return true;
|
|
1271
1420
|
}
|
|
1272
1421
|
/** Confirmation belongs to this exact action, never a standing grant or model assertion. */
|
|
1273
1422
|
confirmWorkflow(sessionId, description, signal) {
|
|
@@ -1408,7 +1557,10 @@ export class SessionHost {
|
|
|
1408
1557
|
const record = this.record(sessionId);
|
|
1409
1558
|
if (record.lifecycle === 'ended')
|
|
1410
1559
|
throw new CommandRefused('Agent Session has ended');
|
|
1411
|
-
|
|
1560
|
+
const scope = scopeKey(record.scope);
|
|
1561
|
+
if (scope !== resolve(record.scope))
|
|
1562
|
+
throw new Error('Scope changed since selection; refusing redirected execution');
|
|
1563
|
+
return { sessionId, backend: record.backendName, scope, projectId: scopeKey(record.worktree?.repo ?? record.scope), session: record.session };
|
|
1412
1564
|
}
|
|
1413
1565
|
assertWorkflowSession(sessionId, session) {
|
|
1414
1566
|
const record = this.record(sessionId);
|
|
@@ -1665,6 +1817,7 @@ export class SessionHost {
|
|
|
1665
1817
|
// that window is a child process nothing is left to dispose. Not awaited, and cannot be: see
|
|
1666
1818
|
// `SummaryModelSpare.dispose`.
|
|
1667
1819
|
this.summarySpare.dispose();
|
|
1820
|
+
await Promise.all(this.backendFailures);
|
|
1668
1821
|
for (const record of this.sessions.values()) {
|
|
1669
1822
|
if (!record.session)
|
|
1670
1823
|
continue;
|
|
@@ -1691,6 +1844,7 @@ export class SessionHost {
|
|
|
1691
1844
|
...(command.backend === undefined ? {} : { backend: command.backend }),
|
|
1692
1845
|
...(command.modelId === undefined ? {} : { modelId: command.modelId }),
|
|
1693
1846
|
...(command.effort === undefined ? {} : { effort: command.effort }),
|
|
1847
|
+
...(command.permissionMode === undefined ? {} : { permissionMode: command.permissionMode }),
|
|
1694
1848
|
...(command.mcpConnectionIds === undefined ? {} : { mcpConnectionIds: command.mcpConnectionIds }),
|
|
1695
1849
|
...(command.worktree === undefined ? {} : { worktree: command.worktree }),
|
|
1696
1850
|
});
|
|
@@ -1712,6 +1866,8 @@ export class SessionHost {
|
|
|
1712
1866
|
return this.acknowledge(command.sessionId, command.throughVersion);
|
|
1713
1867
|
case "set_model":
|
|
1714
1868
|
return await this.setModel(command.sessionId, command.modelId);
|
|
1869
|
+
case "set_permission_mode":
|
|
1870
|
+
return await this.setPermissionMode(command.sessionId, command.mode);
|
|
1715
1871
|
case "set_effort":
|
|
1716
1872
|
return await this.setEffort(command.sessionId, command.effort);
|
|
1717
1873
|
case "pull_branch":
|
|
@@ -1796,13 +1952,17 @@ export class SessionHost {
|
|
|
1796
1952
|
throw new Error('Unknown Agent Session');
|
|
1797
1953
|
return structuredClone((this.mcpConnections?.() ?? []).filter(connection => record.mcpConnectionIds?.includes(connection.id)));
|
|
1798
1954
|
}
|
|
1799
|
-
|
|
1955
|
+
/** Include an SDK-supplied owning root in every local execution's filesystem policy. */
|
|
1956
|
+
filesystemStateRoot() { return this.store?.root; }
|
|
1957
|
+
/** A host without configured Settings keeps the safe, restricted library default. */
|
|
1958
|
+
filesystemIsolationEnabled() { return this.filesystemIsolation?.() ?? true; }
|
|
1959
|
+
async openWorkflowMcp(id, connectionId, isolationEnabled = this.filesystemIsolationEnabled()) {
|
|
1800
1960
|
const connection = this.workflowMcpConnections(id).find(connection => connection.id === connectionId);
|
|
1801
1961
|
if (!connection)
|
|
1802
1962
|
throw new Error('MCP connection is removed or disabled for this Agent Session. Enable it in the Agent Session settings and reconfigure the step.');
|
|
1803
1963
|
const { McpSession } = await import("../backend/mcp.js");
|
|
1804
1964
|
const scope = this.workflowSession(id).scope;
|
|
1805
|
-
return new McpSession([connection], scope, this.mcpAuth ? connection => this.mcpAuth.provider(connection) : undefined, true, this.resolveSecret);
|
|
1965
|
+
return new McpSession([connection], scope, this.mcpAuth ? connection => this.mcpAuth.provider(connection) : undefined, true, this.resolveSecret, undefined, this.filesystemStateRoot(), isolationEnabled);
|
|
1806
1966
|
}
|
|
1807
1967
|
mcpStatus(id) {
|
|
1808
1968
|
const record = this.sessions.get(id);
|
|
@@ -1836,14 +1996,66 @@ export class SessionHost {
|
|
|
1836
1996
|
delete record.mcpReady;
|
|
1837
1997
|
});
|
|
1838
1998
|
}
|
|
1999
|
+
async backendFailed(record, session) {
|
|
2000
|
+
if (record.session !== session)
|
|
2001
|
+
return;
|
|
2002
|
+
this.captureResumeToken(record);
|
|
2003
|
+
record.session = undefined;
|
|
2004
|
+
record.lifecycle = "dormant";
|
|
2005
|
+
record.turnInFlight = false;
|
|
2006
|
+
record.queue.length = 0;
|
|
2007
|
+
try {
|
|
2008
|
+
await this.stopBackendSession(record.scope, session, record.id);
|
|
2009
|
+
}
|
|
2010
|
+
finally {
|
|
2011
|
+
this.closeTornTurn(record, record.log.since(0), "error");
|
|
2012
|
+
const marker = record.log.append({ type: "session_dormant", reason: "backend worker lost" });
|
|
2013
|
+
this.markAttention(record, "Failed", `backend-loss:${record.backendEpoch}`, marker.at);
|
|
2014
|
+
this.touch(record);
|
|
2015
|
+
}
|
|
2016
|
+
}
|
|
2017
|
+
async startPermissionBackend(record) {
|
|
2018
|
+
try {
|
|
2019
|
+
return await this.startBackendSession(record);
|
|
2020
|
+
}
|
|
2021
|
+
catch (error) {
|
|
2022
|
+
if (record.backendName !== "claude" || record.permissionMode !== "auto" || !(error instanceof (await import("../backend/permission-errors.js")).AutoPermissionUnavailable))
|
|
2023
|
+
throw error;
|
|
2024
|
+
record.permissionMode = "ask";
|
|
2025
|
+
const fallback = [
|
|
2026
|
+
{ type: "notice", level: "warn", text: `Claude Auto permissions unavailable: ${String(error)}. Using Ask.` },
|
|
2027
|
+
{ type: "permission_mode_changed", mode: "ask" },
|
|
2028
|
+
];
|
|
2029
|
+
// Creation must still open with session_started. A Revive already has a transcript: write
|
|
2030
|
+
// its effective policy now, even if the replacement backend fails and the buffer is lost.
|
|
2031
|
+
if (record.log.lastSeq === 0)
|
|
2032
|
+
record.buffered?.push(...fallback);
|
|
2033
|
+
else
|
|
2034
|
+
for (const event of fallback)
|
|
2035
|
+
record.log.append(event);
|
|
2036
|
+
this.persist(record);
|
|
2037
|
+
return await this.startBackendSession(record);
|
|
2038
|
+
}
|
|
2039
|
+
}
|
|
1839
2040
|
async startBackendSession(record) {
|
|
2041
|
+
record.endedTurnIds = new Set();
|
|
1840
2042
|
const backend = this.backendFor(record.backendName);
|
|
1841
2043
|
const { McpSession } = await import("../backend/mcp.js");
|
|
1842
|
-
const mcp = new McpSession((this.mcpConnections?.() ?? []).filter((connection) => record.mcpConnectionIds?.includes(connection.id)), record.scope, this.mcpAuth ? (connection) => this.mcpAuth.provider(connection) : undefined, false, this.resolveSecret);
|
|
2044
|
+
const mcp = new McpSession((this.mcpConnections?.() ?? []).filter((connection) => record.mcpConnectionIds?.includes(connection.id)), record.scope, this.mcpAuth ? (connection) => this.mcpAuth.provider(connection) : undefined, false, this.resolveSecret, undefined, this.filesystemStateRoot(), this.filesystemIsolationEnabled());
|
|
1843
2045
|
record.mcp = mcp;
|
|
1844
2046
|
const openingMcp = mcp.open();
|
|
2047
|
+
const autoCompaction = this.autoCompaction?.(backend.name);
|
|
2048
|
+
const compactionModelId = this.compactionModel?.(backend.name);
|
|
2049
|
+
let attached;
|
|
1845
2050
|
const session = await backend.create({
|
|
1846
2051
|
mcp,
|
|
2052
|
+
onFailure: () => {
|
|
2053
|
+
if (!attached || record.session !== attached)
|
|
2054
|
+
return;
|
|
2055
|
+
const stopped = this.backendFailed(record, attached).catch(() => { });
|
|
2056
|
+
this.backendFailures.add(stopped);
|
|
2057
|
+
void stopped.finally(() => this.backendFailures.delete(stopped));
|
|
2058
|
+
},
|
|
1847
2059
|
workflow: {
|
|
1848
2060
|
inspect: input => { this.assertWorkflowSession(record.id, session); if (!this.workflowOwner)
|
|
1849
2061
|
throw new Error('Workflow execution is unavailable'); return this.workflowOwner.parent(record.id).inspect(input); },
|
|
@@ -1855,10 +2067,15 @@ export class SessionHost {
|
|
|
1855
2067
|
throw new Error('Workflow execution is unavailable'); return this.workflowOwner.parent(record.id).relayPermission(input, signal); },
|
|
1856
2068
|
},
|
|
1857
2069
|
scope: record.scope,
|
|
1858
|
-
emit: (event) =>
|
|
1859
|
-
|
|
2070
|
+
emit: (event) => {
|
|
2071
|
+
if (!attached || record.session === attached)
|
|
2072
|
+
this.onBackendEvent(record.id, event);
|
|
2073
|
+
},
|
|
2074
|
+
...(autoCompaction === undefined ? {} : { autoCompaction }),
|
|
2075
|
+
...(compactionModelId === undefined ? {} : { compactionModelId }),
|
|
1860
2076
|
...(record.modelId === undefined ? {} : { modelId: record.modelId }),
|
|
1861
2077
|
...(record.effort === undefined ? {} : { effort: record.effort }),
|
|
2078
|
+
permissionMode: record.permissionMode,
|
|
1862
2079
|
...(record.resumeToken === undefined ? {} : { resume: record.resumeToken }),
|
|
1863
2080
|
...(record.spend === undefined ? {} : { priorSpend: record.spend }),
|
|
1864
2081
|
...(this.store ? { stateDir: this.store.backendDir(record.id) } : {}),
|
|
@@ -1868,6 +2085,7 @@ export class SessionHost {
|
|
|
1868
2085
|
? { standingAuthorisations: this.standingAuthorisations() }
|
|
1869
2086
|
: {}),
|
|
1870
2087
|
}).catch(async (error) => { await mcp.dispose(); throw error; });
|
|
2088
|
+
attached = session;
|
|
1871
2089
|
const dispose = session.dispose.bind(session);
|
|
1872
2090
|
let disposed = false;
|
|
1873
2091
|
session.dispose = async () => { disposed = true; try {
|
|
@@ -1962,7 +2180,7 @@ export class SessionHost {
|
|
|
1962
2180
|
* transcript is append-only (ADR 0001), so we record that we now know it ended instead of
|
|
1963
2181
|
* rewriting the turn that never finished.
|
|
1964
2182
|
*/
|
|
1965
|
-
closeTornTurn(record, entries) {
|
|
2183
|
+
closeTornTurn(record, entries, reason = "aborted") {
|
|
1966
2184
|
this.closeOpenSubagents(record, entries);
|
|
1967
2185
|
this.closeOpenBackgroundCalls(record, entries);
|
|
1968
2186
|
// The daemon-restart case for an Enquiry: nothing was in memory to abandon its callback, and the
|
|
@@ -1972,7 +2190,7 @@ export class SessionHost {
|
|
|
1972
2190
|
const openTurn = openTurnId(entries);
|
|
1973
2191
|
if (!openTurn)
|
|
1974
2192
|
return;
|
|
1975
|
-
record.log.append({ type: "turn_ended", turnId: openTurn, reason
|
|
2193
|
+
record.log.append({ type: "turn_ended", turnId: openTurn, reason });
|
|
1976
2194
|
}
|
|
1977
2195
|
/**
|
|
1978
2196
|
* Close every Subagent the transcript still has running.
|
|
@@ -2043,6 +2261,8 @@ export class SessionHost {
|
|
|
2043
2261
|
record.openPermissionAttention.clear();
|
|
2044
2262
|
}
|
|
2045
2263
|
async dispatch(record, message) {
|
|
2264
|
+
if (record.permissionChanging)
|
|
2265
|
+
await this.waitForPermissionChange(record);
|
|
2046
2266
|
this.refuseGitOperation(record.scope);
|
|
2047
2267
|
if (!record.session)
|
|
2048
2268
|
throw new Error(`Session ${record.id} has no Backend Session`);
|
|
@@ -2077,6 +2297,9 @@ export class SessionHost {
|
|
|
2077
2297
|
* the note work: it arrives before the model acts either way.
|
|
2078
2298
|
*/
|
|
2079
2299
|
const sent = note === undefined ? text : `${text}\n\n${note}`;
|
|
2300
|
+
const session = record.session;
|
|
2301
|
+
const startingTurn = !record.turnInFlight;
|
|
2302
|
+
const generation = record.turnGeneration = (record.turnGeneration ?? 0) + (startingTurn ? 1 : 0);
|
|
2080
2303
|
record.turnInFlight = true;
|
|
2081
2304
|
record.log.append({
|
|
2082
2305
|
type: "user_message",
|
|
@@ -2104,7 +2327,20 @@ export class SessionHost {
|
|
|
2104
2327
|
}
|
|
2105
2328
|
this.touch(record);
|
|
2106
2329
|
const workflowContext = this.workflowOwner?.context(record.id);
|
|
2107
|
-
|
|
2330
|
+
// Acceptance is durable now. SDK prompt promises may last for the entire turn (including
|
|
2331
|
+
// human input), so never keep the HTTP command open awaiting one. Outcomes belong to the
|
|
2332
|
+
// Presentation Transcript, not to the response that acknowledged this message.
|
|
2333
|
+
const failed = (error) => {
|
|
2334
|
+
if (record.lifecycle !== "live" || record.session !== session || record.turnGeneration !== generation)
|
|
2335
|
+
return;
|
|
2336
|
+
this.recordDispatchFailure(record, error, startingTurn);
|
|
2337
|
+
};
|
|
2338
|
+
try {
|
|
2339
|
+
void session.prompt(workflowContext ? `${sent}\n\n${workflowContext}` : sent, this.loadAttachments(record.id, attachments)).catch(failed);
|
|
2340
|
+
}
|
|
2341
|
+
catch (error) {
|
|
2342
|
+
failed(error);
|
|
2343
|
+
}
|
|
2108
2344
|
}
|
|
2109
2345
|
/**
|
|
2110
2346
|
* The bytes for a dispatch, base64 for whichever SDK is about to receive them.
|
|
@@ -2140,6 +2376,19 @@ export class SessionHost {
|
|
|
2140
2376
|
record.buffered.push(event);
|
|
2141
2377
|
return;
|
|
2142
2378
|
}
|
|
2379
|
+
if (record.lifecycle === "dormant")
|
|
2380
|
+
return;
|
|
2381
|
+
if (event.type === "turn_ended") {
|
|
2382
|
+
const ended = record.endedTurnIds ??= new Set();
|
|
2383
|
+
if (ended.has(event.turnId))
|
|
2384
|
+
return;
|
|
2385
|
+
// A delayed SDK terminal event after our synthetic end must not end a newer turn,
|
|
2386
|
+
// cancel its human requests or release its Steering Queue a second time.
|
|
2387
|
+
ended.add(event.turnId);
|
|
2388
|
+
}
|
|
2389
|
+
if (event.type === "turn_started" || (event.type === "permission" && event.state === "asked")) {
|
|
2390
|
+
record.permissionActivityVersion = (record.permissionActivityVersion ?? 0) + 1;
|
|
2391
|
+
}
|
|
2143
2392
|
const before = this.activityOf(record);
|
|
2144
2393
|
const permissionWasOpen = event.type === "permission" && record.openPermissionAttention.has(event.callId);
|
|
2145
2394
|
const enquiryWasOpen = event.type === "enquiry" && record.openEnquiryAttention.has(event.askId);
|
|
@@ -2182,9 +2431,12 @@ export class SessionHost {
|
|
|
2182
2431
|
* dispatch into it, which is the very thing holding the turn open used to prevent.
|
|
2183
2432
|
*/
|
|
2184
2433
|
if (event.type === "turn_started") {
|
|
2434
|
+
if (!record.turnInFlight)
|
|
2435
|
+
record.turnGeneration = (record.turnGeneration ?? 0) + 1;
|
|
2185
2436
|
record.turnInFlight = true;
|
|
2186
2437
|
}
|
|
2187
2438
|
if (event.type === "turn_ended") {
|
|
2439
|
+
record.turnGeneration = (record.turnGeneration ?? 0) + 1;
|
|
2188
2440
|
this.workflowOwner?.rearmInput?.(sessionId);
|
|
2189
2441
|
for (const pending of this.workflowConfirmations.values())
|
|
2190
2442
|
if (pending.sessionId === sessionId)
|
|
@@ -2285,15 +2537,33 @@ export class SessionHost {
|
|
|
2285
2537
|
this.persist(record);
|
|
2286
2538
|
}
|
|
2287
2539
|
}
|
|
2288
|
-
recordDispatchFailure(record, error) {
|
|
2540
|
+
recordDispatchFailure(record, error, endTurn = true) {
|
|
2541
|
+
if (record.lifecycle === "dormant")
|
|
2542
|
+
return; // Fatal worker loss already recorded the failure.
|
|
2289
2543
|
const before = this.activityOf(record);
|
|
2290
2544
|
const failure = record.log.append({ type: "notice", level: "error", text: errorMessage(error) });
|
|
2545
|
+
if (!endTurn) {
|
|
2546
|
+
// A rejected steering request does not stop the already-running original prompt.
|
|
2547
|
+
this.markAttention(record, "Failed", `dispatch-failure:${failure.seq}`, failure.at);
|
|
2548
|
+
this.touch(record);
|
|
2549
|
+
return;
|
|
2550
|
+
}
|
|
2551
|
+
const turnId = openTurnId(record.log.since(0));
|
|
2552
|
+
if (turnId) {
|
|
2553
|
+
// A backend can reject without sending turn_ended. Close the visible turn too, otherwise
|
|
2554
|
+
// the host is Idle while the composer remains Running forever.
|
|
2555
|
+
this.onBackendEvent(record.id, { type: "turn_ended", turnId, reason: "error" });
|
|
2556
|
+
return;
|
|
2557
|
+
}
|
|
2291
2558
|
record.turnInFlight = false;
|
|
2292
2559
|
this.markAttention(record, "Failed", `dispatch-failure:${failure.seq}`, failure.at);
|
|
2293
2560
|
this.noteResting(record, before);
|
|
2294
2561
|
this.touch(record);
|
|
2562
|
+
void this.drain(record);
|
|
2295
2563
|
}
|
|
2296
2564
|
async drain(record) {
|
|
2565
|
+
if (record.permissionChanging)
|
|
2566
|
+
return;
|
|
2297
2567
|
// Avoid an `await` at all when there is no workflow notification. Yielding here lets a backend
|
|
2298
2568
|
// mint a new turn between the check and the queue shift, which would dispatch into that turn.
|
|
2299
2569
|
if ((this.workflowInputs.has(record.id) || this.workflowNotifications.has(record.id) || this.workflowCompletions.has(record.id)) &&
|
|
@@ -2359,6 +2629,7 @@ export class SessionHost {
|
|
|
2359
2629
|
...(record.resumeToken === undefined ? {} : { resumeToken: record.resumeToken }),
|
|
2360
2630
|
...(record.modelId === undefined ? {} : { modelId: record.modelId }),
|
|
2361
2631
|
...(record.effort === undefined ? {} : { effort: record.effort }),
|
|
2632
|
+
permissionMode: record.permissionMode,
|
|
2362
2633
|
...(record.initialEffortUnconfirmed ? { initialEffortUnconfirmed: true } : {}),
|
|
2363
2634
|
...(record.worktree === undefined ? {} : { worktree: record.worktree }),
|
|
2364
2635
|
};
|