operon-agents-core 0.1.0-alpha.2 → 0.1.0-alpha.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/dist/agent/agent.d.ts +8 -7
- package/dist/agent/compose-hooks.d.ts +10 -1
- package/dist/agent/compose-hooks.js +61 -6
- package/dist/agent/concurrency.js +1 -1
- package/dist/agent/context-report.d.ts +2 -2
- package/dist/agent/durable-state.d.ts +22 -0
- package/dist/agent/durable-state.js +54 -0
- package/dist/agent/index.d.ts +2 -2
- package/dist/agent/index.js +1 -1
- package/dist/agent/instruction-context.d.ts +6 -6
- package/dist/agent/instruction-context.js +23 -23
- package/dist/agent/profile-builtins.js +1 -1
- package/dist/agent/run-support.d.ts +1 -1
- package/dist/agent/run-support.js +6 -5
- package/dist/agent/runner.d.ts +25 -22
- package/dist/agent/runner.js +217 -121
- package/dist/agent/session.d.ts +262 -156
- package/dist/agent/session.js +590 -418
- package/dist/agent/subagent-tools.js +3 -3
- package/dist/agent/subagent.js +28 -13
- package/dist/agent/toolset.d.ts +1 -0
- package/dist/agent/toolset.js +13 -7
- package/dist/agent/workflow/journal.d.ts +2 -2
- package/dist/agent/workflow/journal.js +2 -2
- package/dist/agent/workflow/manager.d.ts +1 -1
- package/dist/agent/workflow/manager.js +1 -1
- package/dist/agent/workflow/prompt.js +2 -2
- package/dist/agent/workflow/sandbox.d.ts +1 -1
- package/dist/agent/workflow/sandbox.js +1 -1
- package/dist/agent/workflow/tool.js +30 -43
- package/dist/agent/worktree.d.ts +8 -8
- package/dist/agent/worktree.js +15 -15
- package/dist/capabilities/assembler.d.ts +29 -5
- package/dist/capabilities/assembler.js +85 -9
- package/dist/capabilities/background/code-task.d.ts +43 -0
- package/dist/capabilities/background/code-task.js +75 -0
- package/dist/capabilities/background/command-task.d.ts +9 -2
- package/dist/capabilities/background/command-task.js +22 -6
- package/dist/capabilities/background/index.d.ts +6 -1
- package/dist/capabilities/background/index.js +26 -20
- package/dist/capabilities/background/manager.d.ts +57 -1
- package/dist/capabilities/background/manager.js +210 -45
- package/dist/capabilities/background/persist-disk.d.ts +1 -1
- package/dist/capabilities/background/persist-disk.js +1 -1
- package/dist/capabilities/background/persist.js +4 -2
- package/dist/capabilities/background/projections.d.ts +16 -0
- package/dist/capabilities/background/projections.js +86 -0
- package/dist/capabilities/background/stall-watchdog.d.ts +41 -0
- package/dist/capabilities/background/stall-watchdog.js +85 -0
- package/dist/capabilities/background/task.d.ts +8 -7
- package/dist/capabilities/background/tools.js +33 -7
- package/dist/capabilities/capability-data.d.ts +52 -0
- package/dist/capabilities/capability-data.js +88 -0
- package/dist/capabilities/capability-state.d.ts +2 -4
- package/dist/capabilities/capability-state.js +5 -23
- package/dist/capabilities/capability.d.ts +203 -38
- package/dist/capabilities/compaction/index.js +10 -4
- package/dist/capabilities/compaction/service.d.ts +20 -5
- package/dist/capabilities/compaction/service.js +27 -11
- package/dist/capabilities/goal/goal-store.d.ts +76 -12
- package/dist/capabilities/goal/goal-store.js +137 -53
- package/dist/capabilities/goal/index.d.ts +1 -1
- package/dist/capabilities/goal/index.js +30 -7
- package/dist/capabilities/index.d.ts +9 -6
- package/dist/capabilities/index.js +4 -3
- package/dist/capabilities/plan/index.js +22 -5
- package/dist/capabilities/plan/plan-mode.d.ts +30 -9
- package/dist/capabilities/plan/plan-mode.js +57 -32
- package/dist/capabilities/plan/tools.js +1 -1
- package/dist/capabilities/skills/flow-provider.js +3 -3
- package/dist/capabilities/skills/index.d.ts +13 -1
- package/dist/capabilities/skills/index.js +30 -21
- package/dist/capabilities/skills/parser.d.ts +2 -2
- package/dist/capabilities/skills/parser.js +3 -3
- package/dist/capabilities/skills/registry.d.ts +5 -6
- package/dist/capabilities/skills/registry.js +6 -9
- package/dist/capabilities/skills/scanner.d.ts +3 -3
- package/dist/capabilities/skills/scanner.js +14 -14
- package/dist/capabilities/skills/service.d.ts +2 -1
- package/dist/capabilities/skills/service.js +3 -3
- package/dist/capabilities/skills/skill-tool.d.ts +2 -0
- package/dist/capabilities/skills/skill-tool.js +1 -1
- package/dist/capabilities/task/index.js +2 -1
- package/dist/capabilities/task/persist-disk.d.ts +1 -1
- package/dist/capabilities/task/persist-disk.js +1 -1
- package/dist/capabilities/task/persist.js +1 -1
- package/dist/capabilities/todo/index.js +11 -6
- package/dist/capabilities/todo/injector.js +2 -1
- package/dist/capabilities/todo/todo-store.d.ts +28 -7
- package/dist/capabilities/todo/todo-store.js +44 -11
- package/dist/capabilities/todo/tools.js +8 -3
- package/dist/capabilities/tool-provider.d.ts +3 -3
- package/dist/capabilities/user-hooks/engine.d.ts +3 -3
- package/dist/capabilities/user-hooks/engine.js +7 -7
- package/dist/capabilities/user-hooks/index.js +2 -1
- package/dist/capabilities/workflow/index.d.ts +5 -3
- package/dist/capabilities/workflow/index.js +3 -2
- package/dist/commands/index.js +34 -32
- package/dist/config/index.d.ts +1 -1
- package/dist/config/provider-manager.js +0 -28
- package/dist/config/schema.d.ts +53 -4
- package/dist/config/schema.js +53 -1
- package/dist/events/events.d.ts +43 -11
- package/dist/events/events.js +1 -0
- package/dist/events/index.d.ts +2 -2
- package/dist/events/index.js +1 -1
- package/dist/events/projection.d.ts +49 -1
- package/dist/events/projection.js +144 -19
- package/dist/events/publisher.js +2 -21
- package/dist/home.d.ts +1 -1
- package/dist/home.js +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.js +2 -1
- package/dist/internal.d.ts +5 -2
- package/dist/internal.js +5 -2
- package/dist/llm/define-model.d.ts +4 -0
- package/dist/llm/define-model.js +63 -25
- package/dist/llm/index.d.ts +1 -0
- package/dist/llm/index.js +1 -0
- package/dist/llm/model.d.ts +2 -0
- package/dist/llm/provider.d.ts +17 -0
- package/dist/llm/provider.js +14 -0
- package/dist/llm/retry.js +1 -1
- package/dist/loop/context.d.ts +21 -1
- package/dist/loop/context.js +47 -9
- package/dist/loop/events.d.ts +5 -1
- package/dist/loop/index.d.ts +2 -2
- package/dist/loop/index.js +1 -1
- package/dist/loop/interruption.d.ts +9 -4
- package/dist/loop/interruption.js +11 -25
- package/dist/loop/run-turn.d.ts +16 -3
- package/dist/loop/run-turn.js +13 -4
- package/dist/loop/steer.d.ts +78 -12
- package/dist/loop/steer.js +101 -38
- package/dist/loop/tool-call.d.ts +13 -2
- package/dist/loop/tool-call.js +135 -5
- package/dist/loop/turn-step.d.ts +13 -2
- package/dist/loop/turn-step.js +29 -7
- package/dist/loop/types.d.ts +6 -0
- package/dist/mcp/auth-tool.d.ts +3 -1
- package/dist/mcp/auth-tool.js +2 -2
- package/dist/mcp/capability.d.ts +13 -0
- package/dist/mcp/capability.js +36 -17
- package/dist/mcp/config-loader.d.ts +5 -5
- package/dist/mcp/config-loader.js +17 -17
- package/dist/mcp/credentials.d.ts +35 -0
- package/dist/mcp/credentials.js +2 -0
- package/dist/mcp/filter.d.ts +2 -2
- package/dist/mcp/index.d.ts +4 -3
- package/dist/mcp/index.js +1 -1
- package/dist/mcp/manager.d.ts +108 -6
- package/dist/mcp/manager.js +262 -18
- package/dist/mcp/oauth/callback-server.d.ts +10 -1
- package/dist/mcp/oauth/callback-server.js +82 -16
- package/dist/mcp/oauth/index.d.ts +2 -2
- package/dist/mcp/oauth/provider.d.ts +18 -0
- package/dist/mcp/oauth/provider.js +31 -1
- package/dist/mcp/oauth/service.d.ts +9 -3
- package/dist/mcp/oauth/service.js +29 -4
- package/dist/mcp/sdk-transport.js +1 -1
- package/dist/mcp/server.js +1 -1
- package/dist/permission/auto-approver/prompts-data.d.ts +1 -1
- package/dist/permission/auto-approver/prompts-data.js +1 -1
- package/dist/permission/manager.d.ts +5 -3
- package/dist/permission/manager.js +7 -3
- package/dist/permission/policies.d.ts +2 -2
- package/dist/permission/policies.js +4 -4
- package/dist/plugins/fields.d.ts +14 -0
- package/dist/plugins/fields.js +30 -0
- package/dist/plugins/hooks.d.ts +2 -2
- package/dist/plugins/hooks.js +12 -12
- package/dist/plugins/index.js +1 -0
- package/dist/plugins/manager.d.ts +8 -3
- package/dist/plugins/manager.js +18 -7
- package/dist/plugins/manifest.d.ts +2 -2
- package/dist/plugins/manifest.js +101 -91
- package/dist/plugins/marketplace.js +76 -57
- package/dist/plugins/store.d.ts +3 -3
- package/dist/plugins/store.js +6 -6
- package/dist/protocol/index.d.ts +1 -1
- package/dist/store/catalog-store.d.ts +4 -1
- package/dist/store/catalog-store.js +5 -1
- package/dist/store/checkpointing-store.d.ts +41 -0
- package/dist/store/checkpointing-store.js +86 -0
- package/dist/store/disk-store.d.ts +8 -0
- package/dist/store/disk-store.js +127 -5
- package/dist/store/index.d.ts +3 -2
- package/dist/store/index.js +2 -1
- package/dist/store/log-store.d.ts +9 -1
- package/dist/store/log-store.js +68 -4
- package/dist/store/migrate.d.ts +8 -2
- package/dist/store/migrate.js +9 -2
- package/dist/store/origin.d.ts +31 -6
- package/dist/store/origin.js +0 -14
- package/dist/store/pg.d.ts +1 -0
- package/dist/store/pg.js +37 -2
- package/dist/store/redis.d.ts +1 -0
- package/dist/store/redis.js +30 -0
- package/dist/store/repository.d.ts +13 -1
- package/dist/store/repository.js +45 -2
- package/dist/store/session-catalog.d.ts +4 -0
- package/dist/store/session-catalog.js +6 -0
- package/dist/store/storage.js +3 -0
- package/dist/store/store.d.ts +97 -34
- package/dist/store/store.js +64 -10
- package/dist/telemetry/appender.d.ts +43 -0
- package/dist/telemetry/appender.js +46 -0
- package/dist/telemetry/events.d.ts +142 -0
- package/dist/telemetry/events.js +141 -0
- package/dist/telemetry/index.d.ts +10 -0
- package/dist/telemetry/index.js +6 -0
- package/dist/telemetry/projection.d.ts +23 -0
- package/dist/telemetry/projection.js +185 -0
- package/dist/telemetry/redact.d.ts +20 -0
- package/dist/telemetry/redact.js +40 -0
- package/dist/telemetry/service.d.ts +49 -0
- package/dist/telemetry/service.js +137 -0
- package/dist/testing.d.ts +58 -0
- package/dist/testing.js +123 -0
- package/dist/tool/background.d.ts +9 -6
- package/dist/tool/background.js +7 -1
- package/dist/tool/builtin/ask-user-question.js +6 -5
- package/dist/tool/builtin/bash.d.ts +6 -0
- package/dist/tool/builtin/bash.js +79 -42
- package/dist/tool/builtin/edit.js +82 -109
- package/dist/tool/builtin/glob.js +13 -13
- package/dist/tool/builtin/grep.js +13 -13
- package/dist/tool/builtin/read.js +25 -15
- package/dist/tool/builtin/write.js +49 -33
- package/dist/tool/define.d.ts +14 -8
- package/dist/tool/define.js +8 -2
- package/dist/tool/{machine-base.d.ts → environment-base.d.ts} +37 -37
- package/dist/tool/{machine-base.js → environment-base.js} +45 -119
- package/dist/tool/{machine-local.d.ts → environment-local.d.ts} +9 -8
- package/dist/tool/{machine-local.js → environment-local.js} +60 -81
- package/dist/tool/{machine-null.d.ts → environment-null.d.ts} +9 -9
- package/dist/tool/{machine-null.js → environment-null.js} +9 -9
- package/dist/tool/{machine-ssh.d.ts → environment-ssh.d.ts} +33 -18
- package/dist/tool/{machine-ssh.js → environment-ssh.js} +118 -149
- package/dist/tool/{machine.d.ts → environment.d.ts} +53 -82
- package/dist/tool/environment.js +2 -0
- package/dist/tool/file-freshness.d.ts +33 -19
- package/dist/tool/file-freshness.js +39 -30
- package/dist/tool/filesystem-tools.d.ts +1 -1
- package/dist/tool/filesystem-tools.js +1 -1
- package/dist/tool/git-context.d.ts +2 -2
- package/dist/tool/git-context.js +8 -8
- package/dist/tool/index.d.ts +12 -12
- package/dist/tool/index.js +12 -10
- package/dist/tool/policies/path-access.d.ts +4 -4
- package/dist/tool/policies/path-access.js +12 -12
- package/dist/tool/questions.d.ts +8 -0
- package/dist/tool/search/catalog.d.ts +37 -0
- package/dist/tool/search/catalog.js +182 -0
- package/dist/tool/search/deferral.d.ts +3 -2
- package/dist/tool/search/loaded.d.ts +32 -0
- package/dist/tool/search/loaded.js +96 -0
- package/dist/tool/search/search-tool.d.ts +2 -6
- package/dist/tool/search/search-tool.js +16 -15
- package/dist/tool/shell-env.js +4 -0
- package/dist/tool/support/bash-paths.js +38 -7
- package/dist/tool/support/{machine-ops.d.ts → environment-ops.d.ts} +12 -14
- package/dist/tool/support/{machine-ops.js → environment-ops.js} +21 -2
- package/dist/tool/support/git-worktree.d.ts +3 -3
- package/dist/tool/support/git-worktree.js +6 -6
- package/dist/tool/support/rg-locator.d.ts +6 -6
- package/dist/tool/support/rg-locator.js +6 -6
- package/dist/tool/support/ripgrep-run.d.ts +5 -5
- package/dist/tool/support/ripgrep-run.js +3 -3
- package/dist/tool/support/tool-path.d.ts +3 -3
- package/dist/tool/support/tool-path.js +7 -7
- package/dist/tool/types.d.ts +54 -10
- package/dist/tool/web/fetch-url.js +1 -1
- package/dist/tool/web/web-search.js +1 -1
- package/dist/tool/workspace-spec.d.ts +3 -3
- package/dist/tool/workspace-spec.js +27 -27
- package/dist/tracing/bridge.d.ts +9 -1
- package/dist/tracing/bridge.js +307 -77
- package/dist/tracing/index.d.ts +2 -2
- package/dist/tracing/otel.d.ts +28 -1
- package/dist/tracing/otel.js +150 -38
- package/dist/tracing/processor.d.ts +22 -0
- package/dist/tracing/processor.js +2 -0
- package/dist/tracing/spans.d.ts +54 -0
- package/dist/tracing/spans.js +5 -0
- package/package.json +6 -2
- package/dist/tool/machine.js +0 -15
- package/dist/tool/search/activation.d.ts +0 -13
- package/dist/tool/search/activation.js +0 -31
package/dist/agent/session.js
CHANGED
|
@@ -1,14 +1,19 @@
|
|
|
1
1
|
import { FileFreshnessLedger } from "../tool/file-freshness.js";
|
|
2
2
|
import { PermissionManager } from "../permission/manager.js";
|
|
3
3
|
import { STAGED_POLICY_SLOTS } from "../permission/policies.js";
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
4
|
+
import { NullEnvironment } from "../tool/environment-null.js";
|
|
5
|
+
import { WorkflowManager } from "./workflow/manager.js";
|
|
6
|
+
import { joinAddress, ListenerSink, SessionEventPublisher } from "../events/index.js";
|
|
6
7
|
import { envLogger, noopLogger } from "../logging/index.js";
|
|
7
|
-
import { DEFAULT_ADDRESS } from "../store/index.js";
|
|
8
|
+
import { appendAudit, CheckpointingSessionStore, DEFAULT_ADDRESS, durableStateKey, isCheckpointRecord, readAudit, SESSION_PERMISSION_KEY, SESSION_USAGE_KEY, } from "../store/index.js";
|
|
9
|
+
import { addUsage } from "../loop/usage.js";
|
|
8
10
|
import { eventSinkTracingBridge } from "../tracing/index.js";
|
|
9
|
-
import {
|
|
11
|
+
import { subscribeTelemetryProjection } from "../telemetry/projection.js";
|
|
12
|
+
import { ConversationContext, readShardTail } from "../loop/context.js";
|
|
10
13
|
import { readLog } from "../capabilities/capability-state.js";
|
|
11
|
-
import {
|
|
14
|
+
import { CapabilityData } from "../capabilities/capability-data.js";
|
|
15
|
+
import { DurableStateWriter } from "./durable-state.js";
|
|
16
|
+
import { SteerBus } from "../loop/steer.js";
|
|
12
17
|
import {} from "./subagent.js";
|
|
13
18
|
import { SystemPromptContextCache } from "./instruction-context.js";
|
|
14
19
|
let CLOSE_TIMEOUT_MS = 5_000;
|
|
@@ -30,41 +35,33 @@ export function newSessionId() {
|
|
|
30
35
|
return `s${Date.now().toString(36)}-${sessionCounter.toString(36)}`;
|
|
31
36
|
}
|
|
32
37
|
/**
|
|
33
|
-
*
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
capability;
|
|
40
|
-
constructor(capability) {
|
|
41
|
-
super(`Session has no open "${capability}" capability.`);
|
|
42
|
-
this.name = "CapabilityMissingError";
|
|
43
|
-
this.capability = capability;
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
/**
|
|
47
|
-
* Capability access on a session has two tiers, one rule each:
|
|
48
|
-
* - PROBE — the service getters (`session.cron`, `.goal`, `.plan`, `.backgroundManager`,
|
|
49
|
-
* `.mcp`, …) return `undefined` when that capability is not open. Use these to feature-test.
|
|
50
|
-
* - REQUIRE — the convenience wrappers (`createCronTask()`, `compact()`, `listSkills()`, …)
|
|
51
|
-
* assume the capability and throw {@link CapabilityMissingError} when it is missing.
|
|
38
|
+
* Service access on a session has two tiers, one rule each:
|
|
39
|
+
* - PROBE — `session.service("x")` returns `undefined` when that capability is not open
|
|
40
|
+
* (the capability is not open). Use it to feature-test.
|
|
41
|
+
* - REQUIRE — `session.requireService("x")` and the convenience wrappers (`createCronTask()`,
|
|
42
|
+
* `compact()`, `listSkills()`, …) assume the service and throw `ServiceUnavailableError`
|
|
43
|
+
* when it is missing.
|
|
52
44
|
* The only exceptions are list views documented as degrading to empty when the capability
|
|
53
45
|
* is off (`listWorkflows`, `listSubagents`, `listMcpServers`) — views over durable state
|
|
54
46
|
* that stay meaningful on a session opened without the capability.
|
|
47
|
+
*
|
|
48
|
+
* The session OWNS what its capabilities opened: `close()` runs every `closeSession` in reverse
|
|
49
|
+
* open order, each under a deadline.
|
|
55
50
|
*/
|
|
56
51
|
export class Session {
|
|
57
52
|
id;
|
|
58
|
-
|
|
53
|
+
/** What each open capability published, by capability name. See `service()`. */
|
|
54
|
+
services = new Map();
|
|
55
|
+
/** The host's spawner, used when no background capability is open. */
|
|
56
|
+
injectedSpawner;
|
|
57
|
+
/** Open capabilities in registration order — closed in reverse. */
|
|
58
|
+
openedForClose = [];
|
|
59
|
+
environment;
|
|
59
60
|
store;
|
|
60
61
|
events;
|
|
61
62
|
eventPublisher;
|
|
62
63
|
responder;
|
|
63
64
|
permissionOptions;
|
|
64
|
-
/** Session-lived permission manager: one policy chain + approval memory +
|
|
65
|
-
* mode for the whole session. Constructed in `openCapabilities` (needs capability policy
|
|
66
|
-
* slots and the replayed log); runs reference it instead of building their own. */
|
|
67
|
-
_permission;
|
|
68
65
|
steer;
|
|
69
66
|
signal;
|
|
70
67
|
/** Upstream of `signal`. Fires only via `abort()`; a host signal aborts independently. */
|
|
@@ -72,10 +69,9 @@ export class Session {
|
|
|
72
69
|
logger;
|
|
73
70
|
tracing;
|
|
74
71
|
unsubscribeTracing;
|
|
75
|
-
|
|
72
|
+
unsubscribeTelemetry;
|
|
76
73
|
allCapabilities;
|
|
77
|
-
|
|
78
|
-
// Runtime prompt data is live-Session state, not Agent state: machine identity + cwd isolate
|
|
74
|
+
// Runtime prompt data is live-Session state, not Agent state: environment identity + cwd isolate
|
|
79
75
|
// root/subagent/worktree frames, and the date stays fixed for the Session's lifetime.
|
|
80
76
|
systemPromptContexts = new SystemPromptContextCache();
|
|
81
77
|
// Live in-memory conversation context per address, kept across turns so a long-lived session
|
|
@@ -91,91 +87,173 @@ export class Session {
|
|
|
91
87
|
// has not "read" what its parent read, so ledgers are never shared across addresses.
|
|
92
88
|
fileLedgers = new Map();
|
|
93
89
|
modelOverride;
|
|
94
|
-
/** Caller-supplied one-shot log for open (see
|
|
95
|
-
*
|
|
90
|
+
/** Caller-supplied one-shot log for open (see SessionOpenOptions.preloadedLog); cleared after
|
|
91
|
+
* provisionCapabilities so the array itself is not pinned for the session's lifetime. */
|
|
96
92
|
preloadedLog;
|
|
97
93
|
thinkingOverride;
|
|
98
|
-
|
|
94
|
+
provisionedCapabilities = [];
|
|
99
95
|
isOpen = false;
|
|
96
|
+
/** False once `close()` has started. What the scope's `state` used to answer. */
|
|
97
|
+
get open() {
|
|
98
|
+
return this.isOpen;
|
|
99
|
+
}
|
|
100
|
+
/** The one close in flight (or finished): every `close()` call returns THIS promise. */
|
|
101
|
+
closing;
|
|
100
102
|
runChain = Promise.resolve();
|
|
101
103
|
pendingDiagnostics = [];
|
|
102
|
-
|
|
103
|
-
|
|
104
|
+
/** Builds the context a capability is opened with; set by `openCapabilities`, reused by attach. */
|
|
105
|
+
contextFor;
|
|
106
|
+
/** Runs currently holding an assembly of `capabilities` — see `enterRun` / `exitRun`. */
|
|
107
|
+
activeRuns = 0;
|
|
108
|
+
/** Attach/detach requests waiting for a moment with no run in flight. */
|
|
109
|
+
pendingChanges = [];
|
|
110
|
+
/** Serializes applied changes, and lets `close()` wait for the one in progress. */
|
|
111
|
+
changeChain = Promise.resolve();
|
|
112
|
+
// Most-recent context-window breakdown, stamped by the Runner at each turn boundary and from
|
|
113
|
+
// each step's final request. Undefined until the first turn assembles a request.
|
|
104
114
|
lastContextBreakdown;
|
|
105
|
-
|
|
115
|
+
/** Built at the end of `open`, once every capability's policies are in. */
|
|
116
|
+
permissionManager;
|
|
117
|
+
/** The mode set at RUNTIME (`setPermissionMode`, or restored from one) — what is persisted.
|
|
118
|
+
* A mode that only came from the host's options is not session state: reopening with
|
|
119
|
+
* different options must still take effect. */
|
|
120
|
+
explicitPermissionMode;
|
|
121
|
+
/** The root agent's usage across the session's whole life, stored as `session:usage`. */
|
|
122
|
+
totalUsage;
|
|
123
|
+
/** Beneath the publisher: stamps checkpoints, and folds each shard's lifecycle for them. */
|
|
124
|
+
checkpointing;
|
|
125
|
+
/** Writes capability and session current state to the store's key/value side. */
|
|
126
|
+
durable;
|
|
127
|
+
/** Each stateful capability's `durableState`, by name — registered when it is restored. */
|
|
128
|
+
durableOwners = new Map();
|
|
129
|
+
constructor(id, signal, ownController, publisher, checkpointing, environment, opts) {
|
|
106
130
|
this.id = id;
|
|
107
|
-
this.machine = machine;
|
|
108
|
-
this.ownController = ownController;
|
|
109
|
-
this.eventPublisher = eventPublisher;
|
|
110
|
-
this.store = eventPublisher.store;
|
|
111
|
-
this.events = eventPublisher;
|
|
112
|
-
this.tracing = cfg.tracing;
|
|
113
|
-
this.unsubscribeTracing = cfg.tracing === undefined ? undefined : eventSinkTracingBridge(this.events, cfg.tracing);
|
|
114
|
-
this.responder = cfg.responder;
|
|
115
|
-
this.permissionOptions = cfg.permission;
|
|
116
|
-
this.steer = steer;
|
|
117
|
-
// Every enqueue — user steer/follow-up, cron fire, background settle — surfaces on the
|
|
118
|
-
// event stream, so clients can render a pending queue and later match `origin.steerId`
|
|
119
|
-
// on the consuming `message.appended` to know when the model actually saw it.
|
|
120
|
-
steer.setEnqueueListener((item, channel) => {
|
|
121
|
-
void this.events.emit({
|
|
122
|
-
type: "steer.queued",
|
|
123
|
-
steerId: item.id,
|
|
124
|
-
channel,
|
|
125
|
-
origin: steerOriginToPromptOrigin(item.origin, item.id),
|
|
126
|
-
message: item.message,
|
|
127
|
-
address: "main",
|
|
128
|
-
sessionId: id,
|
|
129
|
-
});
|
|
130
|
-
});
|
|
131
|
-
this.injectedBackground = cfg.background;
|
|
132
131
|
this.signal = signal;
|
|
132
|
+
this.ownController = ownController;
|
|
133
|
+
this.environment = environment;
|
|
134
|
+
this.eventPublisher = publisher;
|
|
135
|
+
// The publishing wrapper around the host's store: record-backed events surface on `events` when
|
|
136
|
+
// the append commits, so everything in the session writes through THIS store. Beneath it, the
|
|
137
|
+
// checkpointing wrapper, so every history checkpoint carries the shard's lifecycle — it sees
|
|
138
|
+
// the lifecycle records the publisher journals, too.
|
|
139
|
+
this.store = this.eventPublisher.store;
|
|
140
|
+
this.checkpointing = checkpointing;
|
|
141
|
+
this.events = this.eventPublisher;
|
|
142
|
+
this.tracing = opts.tracing;
|
|
143
|
+
this.unsubscribeTracing = this.tracing === undefined ? undefined : eventSinkTracingBridge(this.events, this.tracing);
|
|
144
|
+
// Product telemetry rides the same stream. One subscription per session; the projection
|
|
145
|
+
// tells sub-agents apart by address. `resumed` is the one fact the stream cannot tell.
|
|
146
|
+
const telemetry = opts.telemetry;
|
|
147
|
+
this.unsubscribeTelemetry =
|
|
148
|
+
telemetry === undefined
|
|
149
|
+
? undefined
|
|
150
|
+
: subscribeTelemetryProjection(this.events, telemetry.withContext({ session_id: id }), { resumed: opts.resumed === true });
|
|
151
|
+
this.responder = opts.responder;
|
|
152
|
+
this.injectedSpawner = opts.spawner;
|
|
153
|
+
this.permissionOptions = opts.permissionOptions;
|
|
154
|
+
this.steer = opts.steer ?? new SteerBus();
|
|
155
|
+
// Every enqueue — user steer/follow-up, cron fire, background settle, a managed delivery —
|
|
156
|
+
// is journaled as a `steer.queued` record and surfaces on the event stream. The write is
|
|
157
|
+
// handed back so the producer's receipt can settle on durability; clients render a pending
|
|
158
|
+
// queue from the events and match `origin.steerId` on the consuming `message.appended` to
|
|
159
|
+
// know when the model actually saw it. `steer.queued` is a persisted lifecycle event, so
|
|
160
|
+
// this one emit is both the record and the broadcast.
|
|
161
|
+
this.steer.setEnqueueListener((item) => this.events.emit({
|
|
162
|
+
type: "steer.queued",
|
|
163
|
+
steerId: item.id,
|
|
164
|
+
channel: item.channel,
|
|
165
|
+
origin: item.origin,
|
|
166
|
+
message: item.message,
|
|
167
|
+
address: "main",
|
|
168
|
+
sessionId: id,
|
|
169
|
+
}));
|
|
133
170
|
// Env fallback (`AGENTS_LOG`) is resolved here so every entry point — direct `Session.open`,
|
|
134
|
-
// the Runner's ephemeral session, or the harness — honors it from one place.
|
|
135
|
-
|
|
136
|
-
this.
|
|
137
|
-
this.
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
171
|
+
// the Runner's ephemeral session, or the harness — honors it from one place. The harness
|
|
172
|
+
// normally passes its logger in; a session opened directly has nothing else to fall back on.
|
|
173
|
+
this.logger = opts.logger ?? envLogger() ?? noopLogger;
|
|
174
|
+
this.durable = new DurableStateWriter(this.store, this.logger);
|
|
175
|
+
this.allCapabilities = opts.capabilities ?? [];
|
|
176
|
+
this.preloadedLog = opts.preloadedLog;
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Open a session. Everything it depends on arrives in `opts`; `open` fills in the defaults for
|
|
180
|
+
* whatever is missing, builds the session's own objects (signal, event publisher, log reader,
|
|
181
|
+
* controls), opens every capability in order, then builds the permission manager.
|
|
182
|
+
*/
|
|
183
|
+
static async open(opts = {}) {
|
|
184
|
+
const id = opts.sessionId ?? newSessionId();
|
|
142
185
|
// The session owns a cancel handle of its own, downstream of whatever the host passed in:
|
|
143
186
|
// `session.abort()` stops the session without taking the host's signal away from it, and a
|
|
144
187
|
// host abort still propagates. `AbortSignal.any` owns the listener lifetime for us.
|
|
145
188
|
const ownController = new AbortController();
|
|
146
|
-
const signal =
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
189
|
+
const signal = opts.signal === undefined ? ownController.signal : AbortSignal.any([opts.signal, ownController.signal]);
|
|
190
|
+
// Resolved here rather than in the constructor because a factory is async and needs the id.
|
|
191
|
+
const environment = opts.environment === undefined
|
|
192
|
+
? new NullEnvironment()
|
|
193
|
+
: typeof opts.environment === "function"
|
|
194
|
+
? await opts.environment({ sessionId: id, signal })
|
|
195
|
+
: opts.environment;
|
|
196
|
+
// The publisher is the session's OWN object — one producer, one consumer, both inside this
|
|
197
|
+
// class — so it is built here and held as a field.
|
|
198
|
+
const checkpointing = opts.store === undefined ? undefined : new CheckpointingSessionStore(opts.store, id);
|
|
199
|
+
const publisher = new SessionEventPublisher(id, opts.events ?? new ListenerSink(), checkpointing, opts.eventPublication ?? "immediate");
|
|
200
|
+
const session = new Session(id, signal, ownController, publisher, checkpointing, environment, opts);
|
|
153
201
|
await session.openCapabilities();
|
|
154
202
|
return session;
|
|
155
203
|
}
|
|
204
|
+
/**
|
|
205
|
+
* Build every capability's declared services and register them.
|
|
206
|
+
*
|
|
207
|
+
* Each capability is handed its own view of the session: the shared objects plus a
|
|
208
|
+
* `state` / `records` / `record` partitioned by its name. The per-RUN pair is `start`/`stop`,
|
|
209
|
+
* which the assembler drives.
|
|
210
|
+
*/
|
|
156
211
|
async openCapabilities() {
|
|
157
|
-
//
|
|
158
|
-
//
|
|
159
|
-
//
|
|
160
|
-
//
|
|
161
|
-
//
|
|
162
|
-
|
|
212
|
+
// History reads `main` from its newest checkpoint on — the history after it is
|
|
213
|
+
// self-contained, so nothing before it is needed. A caller-preloaded log already holds those
|
|
214
|
+
// records; only the WHOLE log stays lazy, for a capability that asks for it
|
|
215
|
+
// (`SessionContext.logRecords`). State is not in the log at all: each owner reads its current
|
|
216
|
+
// value from the store's key/value side.
|
|
217
|
+
const preloaded = this.preloadedLog;
|
|
163
218
|
this.preloadedLog = undefined;
|
|
219
|
+
const mainRecords = preloaded !== undefined
|
|
220
|
+
? preloaded.filter((record) => (record.address ?? DEFAULT_ADDRESS) === DEFAULT_ADDRESS)
|
|
221
|
+
: this.store !== undefined
|
|
222
|
+
? await this.readShardForRestore(DEFAULT_ADDRESS)
|
|
223
|
+
: [];
|
|
224
|
+
this.checkpointing?.restoreFrame(DEFAULT_ADDRESS, mainRecords);
|
|
225
|
+
let log;
|
|
164
226
|
const logRecords = async () => {
|
|
165
227
|
if (log === undefined)
|
|
166
228
|
log = await readLog(this.store);
|
|
167
229
|
return log;
|
|
168
230
|
};
|
|
169
|
-
const
|
|
231
|
+
const data = new CapabilityData({
|
|
232
|
+
...(this.store !== undefined ? { store: this.store } : {}),
|
|
233
|
+
readAudit: async () => (this.store !== undefined ? readAudit(this.store) : []),
|
|
234
|
+
append: (body) => this.appendAuditRecord(body),
|
|
235
|
+
});
|
|
236
|
+
const shared = {
|
|
170
237
|
sessionId: this.id,
|
|
171
|
-
|
|
172
|
-
store: this.store,
|
|
238
|
+
environment: this.environment,
|
|
173
239
|
events: this.events,
|
|
174
240
|
signal: this.signal,
|
|
175
241
|
steer: this.steer,
|
|
176
242
|
controls: this.controls(),
|
|
177
243
|
logRecords,
|
|
244
|
+
...(this.store !== undefined ? { store: this.store } : {}),
|
|
245
|
+
...(this.logger !== undefined ? { logger: this.logger } : {}),
|
|
178
246
|
};
|
|
247
|
+
const contextFor = (this.contextFor = (owner) => ({
|
|
248
|
+
...shared,
|
|
249
|
+
state: data.stateFor(owner),
|
|
250
|
+
records: data.recordsFor(owner),
|
|
251
|
+
record: data.recorderFor(owner),
|
|
252
|
+
persistState: (address = DEFAULT_ADDRESS) => this.persistOwnerState(owner, address),
|
|
253
|
+
}));
|
|
254
|
+
// Checked before anything opens, so a refusal has nothing to undo.
|
|
255
|
+
for (const cap of this.allCapabilities)
|
|
256
|
+
assertPoliciesInvariant(cap);
|
|
179
257
|
const opened = [];
|
|
180
258
|
const seen = new Set();
|
|
181
259
|
for (const cap of this.allCapabilities) {
|
|
@@ -190,11 +268,20 @@ export class Session {
|
|
|
190
268
|
}
|
|
191
269
|
seen.add(cap.name);
|
|
192
270
|
try {
|
|
193
|
-
|
|
194
|
-
|
|
271
|
+
// A capability that throws here is absent for the session — its per-run assembly too,
|
|
272
|
+
// since it is not pushed onto `opened`. An `invariant` one is not allowed to be absent,
|
|
273
|
+
// so its failure fails the open instead.
|
|
274
|
+
await this.restoreOwner(cap, DEFAULT_ADDRESS);
|
|
275
|
+
await cap.openSession?.(contextFor(cap.name));
|
|
195
276
|
}
|
|
196
277
|
catch (error) {
|
|
197
|
-
//
|
|
278
|
+
// An `invariant` capability may not be absent, so its failure fails the open — but the
|
|
279
|
+
// capabilities already opened are this session's, and nobody else will close them. Undo
|
|
280
|
+
// them here, newest first, before the error leaves.
|
|
281
|
+
if (cap.contract === "invariant") {
|
|
282
|
+
await this.closeOpened(opened);
|
|
283
|
+
throw error;
|
|
284
|
+
}
|
|
198
285
|
this.pendingDiagnostics.push({
|
|
199
286
|
capability: cap.name,
|
|
200
287
|
phase: "start",
|
|
@@ -204,33 +291,255 @@ export class Session {
|
|
|
204
291
|
this.logger.log("error", `capability "${cap.name}" openSession failed`, { capability: cap.name, phase: "start", error: messageOf(error) });
|
|
205
292
|
continue;
|
|
206
293
|
}
|
|
207
|
-
opened.push(cap);
|
|
208
294
|
if (cap.service !== undefined)
|
|
209
295
|
this.services.set(cap.name, cap.service);
|
|
296
|
+
opened.push(cap);
|
|
210
297
|
}
|
|
211
|
-
this.
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
298
|
+
this.provisionedCapabilities = opened;
|
|
299
|
+
this.openedForClose = opened;
|
|
300
|
+
const [usage, permission] = this.store === undefined
|
|
301
|
+
? [undefined, undefined]
|
|
302
|
+
: await Promise.all([this.store.getState(SESSION_USAGE_KEY), this.store.getState(SESSION_PERMISSION_KEY)]);
|
|
303
|
+
if (usage !== null && usage !== undefined)
|
|
304
|
+
this.totalUsage = usage;
|
|
305
|
+
this.buildPermissionManager(opened, (permission ?? undefined));
|
|
306
|
+
// A session opened without the workflow capability still needs ONE manager per session (the
|
|
307
|
+
// resume journals of every workflow run in the session must land in the same store).
|
|
308
|
+
if (!this.services.has("workflow"))
|
|
309
|
+
this.services.set("workflow", new WorkflowManager(this.store));
|
|
310
|
+
// Seed the main live context from the same records, so the first run appends to it
|
|
311
|
+
// instead of reading the shard a second time.
|
|
312
|
+
if (this.store !== undefined && this.liveContext(DEFAULT_ADDRESS) === undefined) {
|
|
216
313
|
const context = new ConversationContext({
|
|
217
314
|
store: this.store,
|
|
218
315
|
address: DEFAULT_ADDRESS,
|
|
219
316
|
});
|
|
220
|
-
context.loadFromRecords(
|
|
317
|
+
context.loadFromRecords(mainRecords);
|
|
221
318
|
this.setLiveContext(DEFAULT_ADDRESS, context);
|
|
222
319
|
}
|
|
223
320
|
this.isOpen = true;
|
|
224
321
|
}
|
|
322
|
+
/**
|
|
323
|
+
* A shard's records from its newest checkpoint on. A checkpoint written without the shard's
|
|
324
|
+
* lifecycle (by a context outside any session) can restore history but not the open turn, so
|
|
325
|
+
* in that case the whole shard is read and the lifecycle is folded from its head.
|
|
326
|
+
*/
|
|
327
|
+
async readShardForRestore(address) {
|
|
328
|
+
const store = this.store;
|
|
329
|
+
const tail = await readShardTail(store, address);
|
|
330
|
+
const head = tail[0];
|
|
331
|
+
// Complete = it carries the shard's lifecycle (`#frame`).
|
|
332
|
+
if (head === undefined || !isCheckpointRecord(head) || head.checkpoint?.["#frame"] !== undefined)
|
|
333
|
+
return tail;
|
|
334
|
+
return this.readWholeShard(address);
|
|
335
|
+
}
|
|
336
|
+
async readWholeShard(address) {
|
|
337
|
+
const all = [];
|
|
338
|
+
for await (const record of this.store.readRecords({ address }))
|
|
339
|
+
all.push(record);
|
|
340
|
+
return all;
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* Restore `cap`'s state for `address` from the value stored for it. Any write of that value
|
|
344
|
+
* still in flight lands first, so the read is never older than what this process last wrote.
|
|
345
|
+
*/
|
|
346
|
+
async restoreOwner(cap, address) {
|
|
347
|
+
const durable = cap.durableState;
|
|
348
|
+
if (durable === undefined)
|
|
349
|
+
return;
|
|
350
|
+
this.durableOwners.set(cap.name, durable);
|
|
351
|
+
if (this.store === undefined) {
|
|
352
|
+
durable.restore(address, undefined);
|
|
353
|
+
return;
|
|
354
|
+
}
|
|
355
|
+
const key = durableStateKey(cap.name, address);
|
|
356
|
+
await this.durable.settled(key);
|
|
357
|
+
durable.restore(address, (await this.store.getState(key)) ?? undefined);
|
|
358
|
+
}
|
|
359
|
+
/** `SessionContext.persistState` for capability `owner`. */
|
|
360
|
+
persistOwnerState(owner, address) {
|
|
361
|
+
const durable = this.durableOwners.get(owner);
|
|
362
|
+
if (durable === undefined)
|
|
363
|
+
return Promise.resolve();
|
|
364
|
+
return this.durable.write(durableStateKey(owner, address), () => durable.snapshot(address));
|
|
365
|
+
}
|
|
366
|
+
/** The session's runtime permission state as persisted: the runtime mode, and its grants. */
|
|
367
|
+
permissionState() {
|
|
368
|
+
return {
|
|
369
|
+
...(this.explicitPermissionMode !== undefined ? { mode: this.explicitPermissionMode } : {}),
|
|
370
|
+
grants: this.permissionManager?.sessionGrants ?? [],
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
addSessionUsage(usage) {
|
|
374
|
+
const total = (this.totalUsage = this.totalUsage === undefined ? usage : addUsage(this.totalUsage, usage));
|
|
375
|
+
void this.durable.write(SESSION_USAGE_KEY, () => this.totalUsage);
|
|
376
|
+
return total;
|
|
377
|
+
}
|
|
378
|
+
/** The root agent's token usage across the session's whole life — every run, every reopen.
|
|
379
|
+
* Subagents' turns are not in it (each is audited in its own shard). */
|
|
380
|
+
get usage() {
|
|
381
|
+
return this.totalUsage;
|
|
382
|
+
}
|
|
383
|
+
async openFrameContext(address) {
|
|
384
|
+
if (this.store === undefined)
|
|
385
|
+
throw new Error("Session has no store; a frame can only be replayed from a durable log.");
|
|
386
|
+
return this.frameContextFrom(address, await this.readShardForRestore(address));
|
|
387
|
+
}
|
|
388
|
+
/** @internal `openFrameContext` over records the caller already read (the shard from a
|
|
389
|
+
* checkpoint on, or whole). */
|
|
390
|
+
async frameContextFrom(address, records) {
|
|
391
|
+
if (this.store === undefined)
|
|
392
|
+
throw new Error("Session has no store; a frame can only be replayed from a durable log.");
|
|
393
|
+
const context = new ConversationContext({ store: this.store, address });
|
|
394
|
+
context.loadFromRecords(records);
|
|
395
|
+
this.checkpointing?.restoreFrame(address, records);
|
|
396
|
+
// `main`'s owners were restored at open and have been live since. Any other address's frame
|
|
397
|
+
// state (a subagent's todo list) is restored here, from what is stored for that address.
|
|
398
|
+
if (address !== DEFAULT_ADDRESS) {
|
|
399
|
+
for (const cap of this.provisionedCapabilities) {
|
|
400
|
+
try {
|
|
401
|
+
await this.restoreOwner(cap, address);
|
|
402
|
+
}
|
|
403
|
+
catch (error) {
|
|
404
|
+
this.logger.log("warn", `capability "${cap.name}" durableState.restore failed for ${address}`, { capability: cap.name, error: messageOf(error) });
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
return context;
|
|
409
|
+
}
|
|
410
|
+
/** Write a capability's record to the audit shard (about `main`). Best effort: a failure is
|
|
411
|
+
* logged, and `records()` still sees the write, from memory. */
|
|
412
|
+
appendAuditRecord(body) {
|
|
413
|
+
if (this.store === undefined)
|
|
414
|
+
return;
|
|
415
|
+
appendAudit(this.store, body, DEFAULT_ADDRESS).catch((error) => {
|
|
416
|
+
this.logger.log("warn", "capability record failed to persist", { error: messageOf(error) });
|
|
417
|
+
});
|
|
418
|
+
}
|
|
419
|
+
// ==========================================================================
|
|
420
|
+
// Capabilities added and removed while the session is open
|
|
421
|
+
// ==========================================================================
|
|
422
|
+
/**
|
|
423
|
+
* Open `capability` in this live session. With no run in flight that is immediate; otherwise it
|
|
424
|
+
* waits for the last run to stop, so a run never sees its capability set change under it — the
|
|
425
|
+
* next run assembles with it. Resolves once `openSession` has run and the capability is part of
|
|
426
|
+
* the session; rejects, leaving nothing behind, when it throws.
|
|
427
|
+
*
|
|
428
|
+
* Only a `detachable` capability can come and go: an `invariant` one (permission, compaction)
|
|
429
|
+
* is part of the session from open — its policies were folded into the permission manager then.
|
|
430
|
+
*/
|
|
431
|
+
attachCapability(capability) {
|
|
432
|
+
return this.submitChange(() => this.attachNow(capability));
|
|
433
|
+
}
|
|
434
|
+
/** Close and remove a `detachable` capability, at the same quiet point `attachCapability` uses. */
|
|
435
|
+
detachCapability(name) {
|
|
436
|
+
return this.submitChange(() => this.detachNow(name));
|
|
437
|
+
}
|
|
438
|
+
/** @internal The Runner is about to assemble `capabilities` for a run. Pair with `exitRun`. */
|
|
439
|
+
enterRun() {
|
|
440
|
+
this.activeRuns += 1;
|
|
441
|
+
}
|
|
442
|
+
/** @internal The run has stopped its capabilities. The last one out applies queued changes. */
|
|
443
|
+
async exitRun() {
|
|
444
|
+
this.activeRuns = Math.max(0, this.activeRuns - 1);
|
|
445
|
+
if (this.activeRuns === 0)
|
|
446
|
+
await this.drainChanges();
|
|
447
|
+
}
|
|
448
|
+
submitChange(apply) {
|
|
449
|
+
if (this.closing !== undefined || !this.isOpen)
|
|
450
|
+
return Promise.reject(new Error("session is closed"));
|
|
451
|
+
return new Promise((resolve, reject) => {
|
|
452
|
+
this.pendingChanges.push({ apply, resolve, reject });
|
|
453
|
+
if (this.activeRuns === 0)
|
|
454
|
+
void this.drainChanges();
|
|
455
|
+
});
|
|
456
|
+
}
|
|
457
|
+
drainChanges() {
|
|
458
|
+
const next = this.changeChain.then(async () => {
|
|
459
|
+
while (this.pendingChanges.length > 0 && this.activeRuns === 0) {
|
|
460
|
+
const change = this.pendingChanges.shift();
|
|
461
|
+
try {
|
|
462
|
+
if (this.closing !== undefined)
|
|
463
|
+
throw new Error("session is closed");
|
|
464
|
+
await change.apply();
|
|
465
|
+
change.resolve();
|
|
466
|
+
}
|
|
467
|
+
catch (error) {
|
|
468
|
+
change.reject(error);
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
});
|
|
472
|
+
this.changeChain = next.catch(() => undefined);
|
|
473
|
+
return this.changeChain;
|
|
474
|
+
}
|
|
475
|
+
async attachNow(capability) {
|
|
476
|
+
const name = capability.name;
|
|
477
|
+
// Colon-free: the name partitions state and records (`extension:<name>:`), and a colon would
|
|
478
|
+
// let one capability's partition swallow another's.
|
|
479
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9_.-]*$/.test(name)) {
|
|
480
|
+
throw new Error(`capability name "${name}" must be a slug ([A-Za-z0-9_.-], no colons)`);
|
|
481
|
+
}
|
|
482
|
+
if (capability.contract === "invariant") {
|
|
483
|
+
throw new Error(`capability "${name}" is invariant: it is part of the session from open and cannot be attached later`);
|
|
484
|
+
}
|
|
485
|
+
assertPoliciesInvariant(capability);
|
|
486
|
+
if (this.provisionedCapabilities.some((open) => open.name === name)) {
|
|
487
|
+
throw new Error(`a capability named "${name}" is already open in this session`);
|
|
488
|
+
}
|
|
489
|
+
// Same restore as at open: its stored state outlived any earlier detach.
|
|
490
|
+
await this.restoreOwner(capability, DEFAULT_ADDRESS);
|
|
491
|
+
await capability.openSession?.(this.contextFor(name));
|
|
492
|
+
if (capability.service !== undefined)
|
|
493
|
+
this.services.set(name, capability.service);
|
|
494
|
+
this.provisionedCapabilities = [...this.provisionedCapabilities, capability];
|
|
495
|
+
this.openedForClose = [...this.openedForClose, capability];
|
|
496
|
+
}
|
|
497
|
+
async detachNow(name) {
|
|
498
|
+
const capability = this.provisionedCapabilities.find((open) => open.name === name);
|
|
499
|
+
if (capability === undefined)
|
|
500
|
+
throw new Error(`no capability named "${name}" is open in this session`);
|
|
501
|
+
if (capability.contract === "invariant") {
|
|
502
|
+
throw new Error(`capability "${name}" is invariant and cannot be detached`);
|
|
503
|
+
}
|
|
504
|
+
// Out of the session first — nothing assembles it again — then torn down.
|
|
505
|
+
this.provisionedCapabilities = this.provisionedCapabilities.filter((open) => open !== capability);
|
|
506
|
+
this.openedForClose = this.openedForClose.filter((open) => open !== capability);
|
|
507
|
+
if (this.services.get(name) === capability.service)
|
|
508
|
+
this.services.delete(name);
|
|
509
|
+
if (capability.closeSession === undefined)
|
|
510
|
+
return;
|
|
511
|
+
try {
|
|
512
|
+
await withTimeout(Promise.resolve(capability.closeSession("detach")), CLOSE_TIMEOUT_MS);
|
|
513
|
+
}
|
|
514
|
+
catch (error) {
|
|
515
|
+
this.logger.log("warn", `capability "${name}" closeSession failed/timed out on detach`, { capability: name, phase: "stop", error: messageOf(error) });
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
/** Close capabilities in reverse open order, each fault-isolated: used to undo a failed open. */
|
|
519
|
+
async closeOpened(opened) {
|
|
520
|
+
for (const cap of [...opened].reverse()) {
|
|
521
|
+
if (cap.closeSession === undefined)
|
|
522
|
+
continue;
|
|
523
|
+
try {
|
|
524
|
+
await withTimeout(Promise.resolve(cap.closeSession("close")), CLOSE_TIMEOUT_MS);
|
|
525
|
+
}
|
|
526
|
+
catch (error) {
|
|
527
|
+
this.logger.log("warn", `capability "${cap.name}" closeSession failed while undoing a failed open`, {
|
|
528
|
+
capability: cap.name,
|
|
529
|
+
phase: "stop",
|
|
530
|
+
error: messageOf(error),
|
|
531
|
+
});
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
}
|
|
225
535
|
/**
|
|
226
536
|
* Construct the session-lived PermissionManager: capability policy slots are collected from
|
|
227
537
|
* the opened capabilities' static `policies` (session-tier fault isolation: a capability whose
|
|
228
|
-
*
|
|
229
|
-
* policies — they are pure evaluators over session-lived state). Then runtime permission
|
|
230
|
-
* state
|
|
231
|
-
* grants (`permission.record_approval` with scope "session").
|
|
538
|
+
* provision failed contributes nothing; a per-run `start()` failure does NOT retract its
|
|
539
|
+
* policies — they are pure evaluators over session-lived state). Then the runtime permission
|
|
540
|
+
* state stored for the session (`session:permission`) is applied over the host's options.
|
|
232
541
|
*/
|
|
233
|
-
|
|
542
|
+
buildPermissionManager(opened, saved) {
|
|
234
543
|
const overrides = new Map();
|
|
235
544
|
for (const capability of opened) {
|
|
236
545
|
for (const policy of capability.policies ?? []) {
|
|
@@ -255,101 +564,142 @@ export class Session {
|
|
|
255
564
|
overrides.set(policy.name, policy);
|
|
256
565
|
}
|
|
257
566
|
}
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
567
|
+
const options = this.permissionOptions;
|
|
568
|
+
const permission = new PermissionManager({
|
|
569
|
+
...options,
|
|
570
|
+
mode: options?.mode,
|
|
261
571
|
// The Runner-driven path answers approvals via interrupt/resume (or the live responder
|
|
262
572
|
// in onInterrupt) — never inline through the manager, so it gets no responder here.
|
|
263
573
|
responder: undefined,
|
|
264
|
-
cwd:
|
|
265
|
-
pathClass:
|
|
266
|
-
|
|
574
|
+
cwd: options?.cwd ?? safeCwd(this.environment),
|
|
575
|
+
pathClass: options?.pathClass ?? this.environment.pathClass(),
|
|
576
|
+
environment: options?.environment ?? this.environment,
|
|
267
577
|
policyOverrides: overrides,
|
|
268
578
|
logger: this.logger,
|
|
269
579
|
});
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
record.approvalRule !== undefined) {
|
|
280
|
-
this._permission.applyApproval(record.approvalRule, { decision: "approved", scope: "session" });
|
|
281
|
-
}
|
|
282
|
-
}
|
|
580
|
+
this.permissionManager = permission;
|
|
581
|
+
if (saved?.mode !== undefined)
|
|
582
|
+
this.restorePermissionMode(saved.mode);
|
|
583
|
+
for (const rule of saved?.grants ?? [])
|
|
584
|
+
permission.applyApproval(rule, { decision: "approved", scope: "session" });
|
|
585
|
+
}
|
|
586
|
+
restorePermissionMode(mode) {
|
|
587
|
+
this.explicitPermissionMode = mode;
|
|
588
|
+
this.permission.setMode(mode);
|
|
283
589
|
}
|
|
284
|
-
/**
|
|
590
|
+
/**
|
|
591
|
+
* Persist the session's runtime permission state — after an approve-for-session grant, which
|
|
592
|
+
* is already applied in memory (`PermissionManager.applyApproval`); this is the durable half.
|
|
593
|
+
* Not awaited: a lost grant only means the user is asked again. The frame's
|
|
594
|
+
* `permission.record_approval` stays the audit record of who granted it.
|
|
595
|
+
*/
|
|
596
|
+
persistPermissionState() {
|
|
597
|
+
void this.durable.write(SESSION_PERMISSION_KEY, () => this.permissionState());
|
|
598
|
+
}
|
|
599
|
+
/** The session-lived permission manager (policy chain + mode + approval memory). Built by
|
|
600
|
+
* `open` once every capability's policies are known; another session's manager is meaningless,
|
|
601
|
+
* so it is a field rather than a registry entry. */
|
|
285
602
|
get permission() {
|
|
286
|
-
|
|
603
|
+
if (this.permissionManager === undefined)
|
|
604
|
+
throw new Error("the permission manager is built during Session.open");
|
|
605
|
+
return this.permissionManager;
|
|
287
606
|
}
|
|
288
607
|
get capabilities() {
|
|
289
|
-
return this.
|
|
608
|
+
return this.provisionedCapabilities;
|
|
290
609
|
}
|
|
610
|
+
/** PROBE tier: what the capability named `name` published, or undefined when it is not open. */
|
|
291
611
|
service(name) {
|
|
292
612
|
return this.services.get(name);
|
|
293
613
|
}
|
|
294
|
-
/**
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
614
|
+
/** REQUIRE tier: the same, or a throw naming the capability that would have provided it. */
|
|
615
|
+
requireService(name) {
|
|
616
|
+
const found = this.services.get(name);
|
|
617
|
+
if (found === undefined)
|
|
618
|
+
throw new Error(`no capability named "${name}" is open in this session`);
|
|
619
|
+
return found;
|
|
620
|
+
}
|
|
621
|
+
// ── capability services ───────────────────────────────────────────────────────────────
|
|
622
|
+
// One accessor per capability, instead of a facade method per operation.
|
|
623
|
+
//
|
|
624
|
+
// Which tier an accessor belongs to is decided by ONE question: when the capability is not
|
|
625
|
+
// open, is that a FAILURE or an ANSWER?
|
|
626
|
+
// - A failure → REQUIRE (`T`). Asking for a goal on a session with no goal capability is a
|
|
627
|
+
// configuration mistake, and the throw names the capability that provides it. Returning
|
|
628
|
+
// `undefined` here would turn a misconfiguration into a silent no-op.
|
|
629
|
+
// - An answer → PROBE (`T | undefined`). A session with no MCP has no servers to report; a
|
|
630
|
+
// session with no background capability has no past runs. The caller has something
|
|
631
|
+
// sensible to do with "none", and the emptiness stays visible at the call site.
|
|
632
|
+
//
|
|
633
|
+
// To FEATURE-TEST a REQUIRE accessor, use `session.service("goal")`. Not `session.goal?.…`:
|
|
634
|
+
// optional chaining guards a null result, not a throwing getter, so it reads as safe and is
|
|
635
|
+
// not.
|
|
636
|
+
//
|
|
637
|
+
// These accessors are the one place core names capabilities (§3.4 holds for their BEHAVIOUR:
|
|
638
|
+
// the kernel and the assembler know only interfaces). It is a deliberate trade: `session.goal`
|
|
639
|
+
// over `session.requireService("goal")` at 58 call sites, paid for by this class listing eleven
|
|
640
|
+
// capability names. A host's own capability is reached through `session.require(tok)` and
|
|
641
|
+
// needs nothing here.
|
|
642
|
+
//
|
|
643
|
+
// The operations themselves live on the services, where the state they change lives: a goal
|
|
644
|
+
// transition announces itself because `GoalStore` announces it, not because a facade method
|
|
645
|
+
// remembered to.
|
|
646
|
+
/** The workflow manager: the capability's, or the in-memory fallback `open` provides. */
|
|
647
|
+
get workflow() {
|
|
648
|
+
return this.requireService("workflow");
|
|
299
649
|
}
|
|
300
650
|
get goal() {
|
|
301
|
-
return this.
|
|
651
|
+
return this.requireService("goal");
|
|
302
652
|
}
|
|
303
|
-
get
|
|
304
|
-
return this.
|
|
653
|
+
get plan() {
|
|
654
|
+
return this.requireService("plan");
|
|
655
|
+
}
|
|
656
|
+
get todo() {
|
|
657
|
+
return this.requireService("todo");
|
|
658
|
+
}
|
|
659
|
+
get task() {
|
|
660
|
+
return this.requireService("task");
|
|
305
661
|
}
|
|
306
662
|
get skills() {
|
|
307
|
-
return this.
|
|
663
|
+
return this.requireService("skills");
|
|
308
664
|
}
|
|
309
665
|
get plugins() {
|
|
310
|
-
return this.
|
|
666
|
+
return this.requireService("plugins");
|
|
311
667
|
}
|
|
312
|
-
get
|
|
313
|
-
|
|
668
|
+
/** The MCP control plane. Absent when no MCP capability is open — hence `get`, not `require`:
|
|
669
|
+
* a session without MCP has no servers to report, and that is an answer, not a failure. */
|
|
670
|
+
get mcp() {
|
|
671
|
+
return this.service("mcp");
|
|
314
672
|
}
|
|
315
|
-
|
|
316
|
-
return this.
|
|
673
|
+
newWorkflowJournal(runId, parentToolCallId) {
|
|
674
|
+
return this.workflow.newJournal(runId, parentToolCallId);
|
|
317
675
|
}
|
|
318
676
|
get compaction() {
|
|
319
|
-
return this.
|
|
677
|
+
return this.requireService("compaction");
|
|
320
678
|
}
|
|
321
|
-
|
|
322
|
-
|
|
679
|
+
/** The PROBE view of the same service, for the loop: absent when compaction is not open. */
|
|
680
|
+
get compactionView() {
|
|
681
|
+
return this.service("compaction");
|
|
323
682
|
}
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
const background = this.requireCapability(this.backgroundManager, "background");
|
|
329
|
-
return background.list(options.activeOnly ?? false, options.limit);
|
|
330
|
-
}
|
|
331
|
-
/** Past BACKGROUND workflow runs (newest first), from the durable task store. A foreground
|
|
332
|
-
* workflow is a plain `Workflow` tool call — its record is the conversation plus its journal
|
|
333
|
-
* shard — so it is not listed here (its shard stays resumable by runId). */
|
|
334
|
-
async listWorkflows() {
|
|
335
|
-
const manager = this.backgroundManager;
|
|
336
|
-
if (manager === undefined)
|
|
337
|
-
return [];
|
|
338
|
-
const runs = [];
|
|
339
|
-
for (const info of manager.list(false)) {
|
|
340
|
-
const snap = taskToWorkflowSnapshot(info);
|
|
341
|
-
if (snap !== undefined)
|
|
342
|
-
runs.push(snap);
|
|
343
|
-
}
|
|
344
|
-
runs.sort((a, b) => (a.startedAt < b.startedAt ? 1 : a.startedAt > b.startedAt ? -1 : 0));
|
|
345
|
-
return runs;
|
|
683
|
+
/** The spawner the Agent/Workflow tools use: the background capability's manager, else the
|
|
684
|
+
* host-injected `spawner` (`SessionOpenOptions.spawner`). */
|
|
685
|
+
get spawner() {
|
|
686
|
+
return this.service("background") ?? this.injectedSpawner;
|
|
346
687
|
}
|
|
347
|
-
/**
|
|
348
|
-
|
|
349
|
-
|
|
688
|
+
/**
|
|
689
|
+
* The durable task ledger — background tasks, subagents and workflow runs.
|
|
690
|
+
*
|
|
691
|
+
* PROBE tier (`| undefined`), unlike the accessors above, and deliberately: a session opened
|
|
692
|
+
* without the background capability has no past runs, which is an ANSWER — so a caller writes
|
|
693
|
+
* `session.background?.listSubagents() ?? []` and the emptiness is visible at the call site
|
|
694
|
+
* instead of hidden inside a facade method. Callers that genuinely require it (stopping a
|
|
695
|
+
* task, detaching a tool call) should say so with `session.requireService("background")`.
|
|
696
|
+
*/
|
|
697
|
+
get background() {
|
|
698
|
+
return this.service("background");
|
|
350
699
|
}
|
|
351
700
|
/** The most-recent context-window breakdown (system/tools/messages/injections/free), stamped
|
|
352
|
-
* by the Runner at each turn boundary
|
|
701
|
+
* by the Runner at each turn boundary and again from every step's request as sent, after every
|
|
702
|
+
* hook (an extension may rewrite it) — or undefined if no turn has assembled a request yet.
|
|
353
703
|
* A read-only snapshot: it reflects the last turn sent, not a fresh recomputation. */
|
|
354
704
|
getContextBreakdown() {
|
|
355
705
|
return this.lastContextBreakdown;
|
|
@@ -358,49 +708,12 @@ export class Session {
|
|
|
358
708
|
recordContextBreakdown(breakdown) {
|
|
359
709
|
this.lastContextBreakdown = breakdown;
|
|
360
710
|
}
|
|
361
|
-
/** The background subagents of this session, from the durable task store (live + reconciled
|
|
362
|
-
* ghosts). Foreground subagents are plain `Agent` tool calls — their record is the conversation
|
|
363
|
-
* plus their own shard — so they are not listed here (their shard stays resumable by id). */
|
|
364
|
-
async listSubagents() {
|
|
365
|
-
const manager = this.backgroundManager;
|
|
366
|
-
if (manager === undefined)
|
|
367
|
-
return [];
|
|
368
|
-
const records = [];
|
|
369
|
-
for (const info of manager.list(false)) {
|
|
370
|
-
const record = taskToSubagentRecord(info);
|
|
371
|
-
if (record !== undefined)
|
|
372
|
-
records.push(record);
|
|
373
|
-
}
|
|
374
|
-
return records;
|
|
375
|
-
}
|
|
376
|
-
/**
|
|
377
|
-
* Reclassify orphaned background work (spawned by a dead process, never settled) as `lost`
|
|
378
|
-
* through the task store: the manager writes the terminal status back and steers the lost
|
|
379
|
-
* notification (the durable settle record), so later opens won't re-report. Also emits a warning
|
|
380
|
-
* per reclassified subagent. Call when reopening an existing session. Returns the lost subagents
|
|
381
|
-
* (resume any with `Agent(resume="<id>", ...)`).
|
|
382
|
-
*/
|
|
383
|
-
async reconcileSubagents() {
|
|
384
|
-
const manager = this.backgroundManager;
|
|
385
|
-
if (manager === undefined || this.store === undefined)
|
|
386
|
-
return [];
|
|
387
|
-
const lost = [];
|
|
388
|
-
for (const info of await manager.reconcile()) {
|
|
389
|
-
const record = taskToSubagentRecord(info);
|
|
390
|
-
if (record === undefined)
|
|
391
|
-
continue;
|
|
392
|
-
lost.push(record);
|
|
393
|
-
await this.emitControlEvent({
|
|
394
|
-
type: "warning",
|
|
395
|
-
message: `Background subagent "${record.agentId}" (${record.type}) was running when the previous process exited; marked lost. Resume with Agent(resume="${record.agentId}", ...).`,
|
|
396
|
-
});
|
|
397
|
-
}
|
|
398
|
-
return lost;
|
|
399
|
-
}
|
|
400
711
|
// ── Conversation log (flat, linear) ──────────────────────────────────────────────────────
|
|
401
712
|
// The log is a single append-only record stream per address (no branching). `getRecords`
|
|
402
|
-
// exposes it read-only for inspection / transcript rendering
|
|
403
|
-
|
|
713
|
+
// exposes it read-only for inspection / transcript rendering; `getAuditRecords` the audit
|
|
714
|
+
// shard beside it (approvals, permission-mode changes, capability records, diagnostics).
|
|
715
|
+
/** Every record of an address in append order (for rendering the transcript). Without an
|
|
716
|
+
* address, every conversation shard — the audit shard is read with `getAuditRecords`. */
|
|
404
717
|
async getRecords(address) {
|
|
405
718
|
if (this.store === undefined) {
|
|
406
719
|
throw new Error("Session has no store; the conversation log requires a durable store.");
|
|
@@ -410,6 +723,13 @@ export class Session {
|
|
|
410
723
|
records.push(record);
|
|
411
724
|
return records;
|
|
412
725
|
}
|
|
726
|
+
/** The audit shard's records in append order; each names the shard it concerns in `about`. */
|
|
727
|
+
async getAuditRecords() {
|
|
728
|
+
if (this.store === undefined) {
|
|
729
|
+
throw new Error("Session has no store; the audit log requires a durable store.");
|
|
730
|
+
}
|
|
731
|
+
return readAudit(this.store);
|
|
732
|
+
}
|
|
413
733
|
// ── live context cache (perf: append across turns instead of replaying the log) ──
|
|
414
734
|
/** @internal The kept live context for an address, or undefined (cold → caller replays). */
|
|
415
735
|
liveContext(address) {
|
|
@@ -433,20 +753,19 @@ export class Session {
|
|
|
433
753
|
};
|
|
434
754
|
}
|
|
435
755
|
/**
|
|
436
|
-
* Hand a message to the frame running at `address`;
|
|
756
|
+
* Hand a message to the frame running at `address`; undefined when nobody is there.
|
|
437
757
|
*
|
|
438
758
|
* This is the whole seam an external coordinator needs in order to address a subagent: it can
|
|
439
759
|
* already learn who exists from `agent.started` / `agent.ended` (both carry `address`), but it
|
|
440
|
-
* has no way to reach a child's
|
|
760
|
+
* has no way to reach a child's queue — every frame owns a private `SteerBus`. Deliberately
|
|
441
761
|
* knows nothing about peers, rosters or visibility: those are policy, and policy belongs to
|
|
442
762
|
* whoever is coordinating, not to the engine.
|
|
443
763
|
*/
|
|
444
|
-
steerTo(address, content, origin) {
|
|
764
|
+
steerTo(address, content, origin, options) {
|
|
445
765
|
const bus = address === DEFAULT_ADDRESS ? this.steer : this.frameBuses.get(address);
|
|
446
766
|
if (bus === undefined)
|
|
447
|
-
return
|
|
448
|
-
bus.steer(content, origin);
|
|
449
|
-
return true;
|
|
767
|
+
return undefined;
|
|
768
|
+
return bus.steer(content, origin, options);
|
|
450
769
|
}
|
|
451
770
|
/** @internal Cached conversation owner. Durable sessions can always rebuild it from the log. */
|
|
452
771
|
conversationHead() {
|
|
@@ -480,106 +799,8 @@ export class Session {
|
|
|
480
799
|
return ledger;
|
|
481
800
|
}
|
|
482
801
|
/** Resolve environment + AGENTS.md for the active runtime frame, cached for this Session. */
|
|
483
|
-
resolveSystemPromptContext(
|
|
484
|
-
return this.systemPromptContexts.resolve(
|
|
485
|
-
}
|
|
486
|
-
/** A bounded view of the task's authoritative output, with explicit size/truncation metadata. */
|
|
487
|
-
async readBackgroundTaskOutput(taskId, options = {}) {
|
|
488
|
-
const background = this.requireCapability(this.backgroundManager, "background");
|
|
489
|
-
return background.readOutput(taskId, options.maxBytes ?? 16 * 1024);
|
|
490
|
-
}
|
|
491
|
-
/**
|
|
492
|
-
* Everything a task appended since `cursor` — what a live panel polls so each tick
|
|
493
|
-
* carries only what is new, instead of re-fetching the same window. `followable: false`
|
|
494
|
-
* means this task keeps no byte-addressable output; use `readBackgroundTaskOutput` instead.
|
|
495
|
-
*/
|
|
496
|
-
async readBackgroundTaskOutputDelta(taskId, options) {
|
|
497
|
-
const background = this.requireCapability(this.backgroundManager, "background");
|
|
498
|
-
return background.readOutputDelta(taskId, options.cursor, options.maxBytes);
|
|
499
|
-
}
|
|
500
|
-
async stopBackgroundTask(taskId, reason) {
|
|
501
|
-
const background = this.requireCapability(this.backgroundManager, "background");
|
|
502
|
-
return background.stop(taskId, reason);
|
|
503
|
-
}
|
|
504
|
-
/**
|
|
505
|
-
* Move a running, detachable tool call (bash / subagent / workflow) from the foreground into
|
|
506
|
-
* a background task — the "move to background" action. Returns false if no such call is
|
|
507
|
-
* currently in its detachable window (already finished, or not a detachable tool).
|
|
508
|
-
*/
|
|
509
|
-
detachTool(toolCallId) {
|
|
510
|
-
const background = this.requireCapability(this.backgroundManager, "background");
|
|
511
|
-
return background.detach(toolCallId);
|
|
512
|
-
}
|
|
513
|
-
/** Connected MCP servers and their status. Empty when no MCP capability is open. */
|
|
514
|
-
listMcpServers() {
|
|
515
|
-
return this.mcp?.list() ?? [];
|
|
516
|
-
}
|
|
517
|
-
/** Force-reconnect one MCP server by name. Throws if no MCP capability is open. */
|
|
518
|
-
async reconnectMcpServer(name) {
|
|
519
|
-
const mcp = this.requireCapability(this.mcp, "mcp");
|
|
520
|
-
await mcp.reconnect(name);
|
|
521
|
-
}
|
|
522
|
-
async createGoal(input) {
|
|
523
|
-
const goal = this.requireCapability(this.goal, "goal");
|
|
524
|
-
if (input.objective.trim().length === 0)
|
|
525
|
-
throw new Error("Goal objective cannot be empty.");
|
|
526
|
-
if (goal.has())
|
|
527
|
-
goal.update({ status: "complete" });
|
|
528
|
-
let snapshot = goal.update({
|
|
529
|
-
objective: input.objective.trim(),
|
|
530
|
-
completionCriterion: input.completionCriterion?.trim(),
|
|
531
|
-
status: "active",
|
|
532
|
-
});
|
|
533
|
-
if (input.budget !== undefined)
|
|
534
|
-
snapshot = goal.setBudget(normalizeGoalBudget(input.budget));
|
|
535
|
-
if (snapshot === null)
|
|
536
|
-
throw new Error("Goal was not created.");
|
|
537
|
-
await this.emitControlEvent({ type: "goal.updated", snapshot });
|
|
538
|
-
return snapshot;
|
|
539
|
-
}
|
|
540
|
-
async getGoal() {
|
|
541
|
-
const goal = this.requireCapability(this.goal, "goal");
|
|
542
|
-
return goal.snapshot();
|
|
543
|
-
}
|
|
544
|
-
async pauseGoal(options = {}) {
|
|
545
|
-
return this.updateExistingGoal("paused", options.reason);
|
|
546
|
-
}
|
|
547
|
-
async resumeGoal(options = {}) {
|
|
548
|
-
return this.updateExistingGoal("active", options.reason);
|
|
549
|
-
}
|
|
550
|
-
async cancelGoal(options = {}) {
|
|
551
|
-
const goal = this.requireCapability(this.goal, "goal");
|
|
552
|
-
const previous = goal.snapshot();
|
|
553
|
-
if (previous === null)
|
|
554
|
-
return null;
|
|
555
|
-
goal.update({ status: "complete", reason: options.reason });
|
|
556
|
-
await this.emitControlEvent({ type: "goal.updated", snapshot: null });
|
|
557
|
-
return previous;
|
|
558
|
-
}
|
|
559
|
-
async setGoalBudget(budget) {
|
|
560
|
-
const goal = this.requireCapability(this.goal, "goal");
|
|
561
|
-
const snapshot = goal.setBudget(normalizeGoalBudget(budget));
|
|
562
|
-
await this.emitControlEvent({ type: "goal.updated", snapshot });
|
|
563
|
-
return snapshot;
|
|
564
|
-
}
|
|
565
|
-
async setPlanMode(enabled, options = {}) {
|
|
566
|
-
const plan = this.requireCapability(this.plan, "plan");
|
|
567
|
-
if (enabled && !plan.isActive) {
|
|
568
|
-
await plan.enter(options.createFile ?? true);
|
|
569
|
-
}
|
|
570
|
-
else if (!enabled && plan.isActive) {
|
|
571
|
-
plan.exit();
|
|
572
|
-
}
|
|
573
|
-
const snapshot = await plan.data();
|
|
574
|
-
await this.emitControlEvent({ type: "plan.updated", snapshot });
|
|
575
|
-
return snapshot;
|
|
576
|
-
}
|
|
577
|
-
async getPlan() {
|
|
578
|
-
const plan = this.requireCapability(this.plan, "plan");
|
|
579
|
-
return plan.data();
|
|
580
|
-
}
|
|
581
|
-
async clearPlan() {
|
|
582
|
-
return this.setPlanMode(false);
|
|
802
|
+
resolveSystemPromptContext(environment) {
|
|
803
|
+
return this.systemPromptContexts.resolve(environment, this.compactionView?.revision ?? 0);
|
|
583
804
|
}
|
|
584
805
|
/**
|
|
585
806
|
* The `SessionControls` view handed to capabilities that act on the session (the extension
|
|
@@ -589,7 +810,7 @@ export class Session {
|
|
|
589
810
|
controls() {
|
|
590
811
|
return {
|
|
591
812
|
abort: (reason) => this.abort(reason),
|
|
592
|
-
compact: (options) => this.
|
|
813
|
+
compact: async (options) => this.compaction.request(options),
|
|
593
814
|
getContextBreakdown: () => this.getContextBreakdown(),
|
|
594
815
|
setModel: (model) => this.setModel(model),
|
|
595
816
|
setThinking: (level) => this.setThinking(level),
|
|
@@ -605,70 +826,6 @@ export class Session {
|
|
|
605
826
|
return;
|
|
606
827
|
this.ownController.abort(abortReason(reason ?? "session aborted"));
|
|
607
828
|
}
|
|
608
|
-
async compact(options = {}) {
|
|
609
|
-
const compaction = this.requireCapability(this.compaction, "compaction");
|
|
610
|
-
return compaction.request(options);
|
|
611
|
-
}
|
|
612
|
-
async pendingCompaction() {
|
|
613
|
-
const compaction = this.requireCapability(this.compaction, "compaction");
|
|
614
|
-
return compaction.pending();
|
|
615
|
-
}
|
|
616
|
-
async cancelCompaction() {
|
|
617
|
-
const compaction = this.requireCapability(this.compaction, "compaction");
|
|
618
|
-
return compaction.cancel();
|
|
619
|
-
}
|
|
620
|
-
async updateExistingGoal(status, reason) {
|
|
621
|
-
const goal = this.requireCapability(this.goal, "goal");
|
|
622
|
-
if (goal.snapshot() === null)
|
|
623
|
-
return null;
|
|
624
|
-
const snapshot = goal.update({ status, reason });
|
|
625
|
-
await this.emitControlEvent({ type: "goal.updated", snapshot });
|
|
626
|
-
return snapshot;
|
|
627
|
-
}
|
|
628
|
-
async emitControlEvent(body) {
|
|
629
|
-
await this.events.emit({ ...body, address: "main", sessionId: this.id });
|
|
630
|
-
}
|
|
631
|
-
async listSkills() {
|
|
632
|
-
const skills = this.requireCapability(this.skills, "skills");
|
|
633
|
-
return skills.listSkills();
|
|
634
|
-
}
|
|
635
|
-
async activateSkill(nameOrRequest, args) {
|
|
636
|
-
const skills = this.requireCapability(this.skills, "skills");
|
|
637
|
-
const request = typeof nameOrRequest === "string" ? { name: nameOrRequest, ...(args !== undefined ? { args } : {}) } : nameOrRequest;
|
|
638
|
-
return skills.activateSkill(request);
|
|
639
|
-
}
|
|
640
|
-
async listPlugins() {
|
|
641
|
-
const plugins = this.requireCapability(this.plugins, "plugins");
|
|
642
|
-
return plugins.summaries();
|
|
643
|
-
}
|
|
644
|
-
async getPluginInfo(id) {
|
|
645
|
-
const plugins = this.requireCapability(this.plugins, "plugins");
|
|
646
|
-
return plugins.info(id);
|
|
647
|
-
}
|
|
648
|
-
async installPlugin(source) {
|
|
649
|
-
const plugins = this.requireCapability(this.plugins, "plugins");
|
|
650
|
-
const record = await plugins.install(source);
|
|
651
|
-
const summary = plugins.summaries().find((plugin) => plugin.id === record.id);
|
|
652
|
-
if (summary === undefined)
|
|
653
|
-
throw new Error(`Plugin "${record.id}" was installed but no summary was produced.`);
|
|
654
|
-
return summary;
|
|
655
|
-
}
|
|
656
|
-
async setPluginEnabled(id, enabled) {
|
|
657
|
-
const plugins = this.requireCapability(this.plugins, "plugins");
|
|
658
|
-
await plugins.setEnabled(id, enabled);
|
|
659
|
-
}
|
|
660
|
-
async setPluginMcpServerEnabled(id, server, enabled) {
|
|
661
|
-
const plugins = this.requireCapability(this.plugins, "plugins");
|
|
662
|
-
await plugins.setMcpServerEnabled(id, server, enabled);
|
|
663
|
-
}
|
|
664
|
-
async removePlugin(id) {
|
|
665
|
-
const plugins = this.requireCapability(this.plugins, "plugins");
|
|
666
|
-
await plugins.remove(id);
|
|
667
|
-
}
|
|
668
|
-
async reloadPlugins() {
|
|
669
|
-
const plugins = this.requireCapability(this.plugins, "plugins");
|
|
670
|
-
return plugins.reload();
|
|
671
|
-
}
|
|
672
829
|
setModel(model) {
|
|
673
830
|
this.modelOverride = model;
|
|
674
831
|
}
|
|
@@ -685,14 +842,16 @@ export class Session {
|
|
|
685
842
|
* rejection is pre-handled internally, so ignoring it never trips unhandledRejection).
|
|
686
843
|
*/
|
|
687
844
|
setPermissionMode(mode) {
|
|
688
|
-
this.
|
|
845
|
+
this.explicitPermissionMode = mode;
|
|
846
|
+
this.permission.setMode(mode);
|
|
689
847
|
if (this.store === undefined)
|
|
690
848
|
return Promise.resolve();
|
|
691
|
-
|
|
692
|
-
|
|
849
|
+
// The audit trail of the change, best effort; the stored state is what a reopen reads, and
|
|
850
|
+
// what the returned promise waits for.
|
|
851
|
+
appendAudit(this.store, { type: "permission.set_mode", mode }, DEFAULT_ADDRESS).catch((error) => {
|
|
693
852
|
this.logger.log("warn", "failed to journal permission.set_mode", { error: error instanceof Error ? error.message : String(error) });
|
|
694
853
|
});
|
|
695
|
-
return
|
|
854
|
+
return this.durable.write(SESSION_PERMISSION_KEY, () => this.permissionState());
|
|
696
855
|
}
|
|
697
856
|
get modelSetting() {
|
|
698
857
|
return this.modelOverride;
|
|
@@ -701,7 +860,7 @@ export class Session {
|
|
|
701
860
|
return this.thinkingOverride;
|
|
702
861
|
}
|
|
703
862
|
get permissionModeSetting() {
|
|
704
|
-
return this.
|
|
863
|
+
return this.permission.mode;
|
|
705
864
|
}
|
|
706
865
|
drainDiagnostics() {
|
|
707
866
|
return this.pendingDiagnostics.splice(0, this.pendingDiagnostics.length);
|
|
@@ -721,29 +880,29 @@ export class Session {
|
|
|
721
880
|
flushEvents() {
|
|
722
881
|
return this.eventPublisher.flush();
|
|
723
882
|
}
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
883
|
+
/**
|
|
884
|
+
* Close the session: flush telemetry and the store, then close the scope — which disposes
|
|
885
|
+
* every capability provision in reverse order (each under a deadline) and finally the
|
|
886
|
+
* session's own infrastructure. Every call returns the SAME promise, so a second caller
|
|
887
|
+
* (or the facade above) waits for the teardown instead of returning while it is still running.
|
|
888
|
+
*/
|
|
889
|
+
close() {
|
|
890
|
+
if (this.closing !== undefined)
|
|
891
|
+
return this.closing;
|
|
892
|
+
this.closing = this.isOpen ? this.runClose() : Promise.resolve();
|
|
893
|
+
return this.closing;
|
|
894
|
+
}
|
|
895
|
+
async runClose() {
|
|
727
896
|
this.isOpen = false;
|
|
897
|
+
// Nothing queued will be applied now; one already being applied finishes first, so the
|
|
898
|
+
// capability it opens is on the list the teardown below walks.
|
|
899
|
+
for (const change of this.pendingChanges.splice(0))
|
|
900
|
+
change.reject(new Error("session is closed"));
|
|
901
|
+
await this.changeChain;
|
|
728
902
|
this.systemPromptContexts.clear();
|
|
729
903
|
this.unsubscribeTracing?.();
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
continue;
|
|
733
|
-
try {
|
|
734
|
-
await withTimeout(Promise.resolve(cap.closeSession()), CLOSE_TIMEOUT_MS);
|
|
735
|
-
}
|
|
736
|
-
catch (error) {
|
|
737
|
-
this.pendingDiagnostics.push({
|
|
738
|
-
capability: cap.name,
|
|
739
|
-
phase: "stop",
|
|
740
|
-
level: "warn",
|
|
741
|
-
message: `closeSession failed/timed out: ${messageOf(error)}`,
|
|
742
|
-
});
|
|
743
|
-
this.logger.log("warn", `capability "${cap.name}" closeSession failed/timed out`, { capability: cap.name, phase: "stop", error: messageOf(error) });
|
|
744
|
-
}
|
|
745
|
-
}
|
|
746
|
-
this.openedCapabilities = [];
|
|
904
|
+
this.unsubscribeTelemetry?.();
|
|
905
|
+
this.provisionedCapabilities = [];
|
|
747
906
|
try {
|
|
748
907
|
await withTimeout(Promise.resolve(this.tracing?.forceFlush()), CLOSE_TIMEOUT_MS);
|
|
749
908
|
}
|
|
@@ -758,6 +917,7 @@ export class Session {
|
|
|
758
917
|
}
|
|
759
918
|
try {
|
|
760
919
|
await withTimeout(this.eventPublisher.flush(), STORE_FLUSH_TIMEOUT_MS);
|
|
920
|
+
await withTimeout(this.durable.flush(), STORE_FLUSH_TIMEOUT_MS);
|
|
761
921
|
await withTimeout(Promise.resolve(this.store?.flush?.()), STORE_FLUSH_TIMEOUT_MS);
|
|
762
922
|
}
|
|
763
923
|
catch (error) {
|
|
@@ -769,13 +929,26 @@ export class Session {
|
|
|
769
929
|
});
|
|
770
930
|
this.logger.log("warn", "store flush failed/timed out", { capability: "store", phase: "stop", error: messageOf(error) });
|
|
771
931
|
}
|
|
772
|
-
//
|
|
773
|
-
//
|
|
774
|
-
//
|
|
932
|
+
// Capabilities go down in reverse open order, each under CLOSE_TIMEOUT_MS: a straggler is
|
|
933
|
+
// abandoned (and logged) so close() can never hang on one of them, and a failure is isolated
|
|
934
|
+
// so the ones after it still get torn down. The environment is NOT closed here: its lifetime
|
|
935
|
+
// belongs to whoever created it, and a sandbox usually outlives any one session.
|
|
936
|
+
for (const cap of [...this.openedForClose].reverse()) {
|
|
937
|
+
if (cap.closeSession === undefined)
|
|
938
|
+
continue;
|
|
939
|
+
try {
|
|
940
|
+
await withTimeout(Promise.resolve(cap.closeSession("close")), CLOSE_TIMEOUT_MS);
|
|
941
|
+
}
|
|
942
|
+
catch (error) {
|
|
943
|
+
this.pendingDiagnostics.push({ capability: cap.name, phase: "stop", level: "warn", message: `closeSession failed/timed out: ${messageOf(error)}` });
|
|
944
|
+
this.logger.log("warn", `capability "${cap.name}" closeSession failed/timed out`, { capability: cap.name, phase: "stop", error: messageOf(error) });
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
this.services.clear();
|
|
775
948
|
}
|
|
776
|
-
/** Public URL for a port inside the
|
|
949
|
+
/** Public URL for a port inside the environment, or undefined when the backend can't expose one. */
|
|
777
950
|
async resolveExposedPort(port) {
|
|
778
|
-
return await this.
|
|
951
|
+
return await this.environment.exposedPortUrl?.(port);
|
|
779
952
|
}
|
|
780
953
|
}
|
|
781
954
|
function normalizeGoalBudget(input) {
|
|
@@ -802,17 +975,16 @@ function positiveInt(name, value) {
|
|
|
802
975
|
throw new Error(`Goal budget ${name} must be a positive integer.`);
|
|
803
976
|
return value;
|
|
804
977
|
}
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
return typeof cfg.machine === "function" ? await cfg.machine(ctx) : cfg.machine;
|
|
978
|
+
/** A permission rule that can be timed out or detached is one that fails OPEN — see
|
|
979
|
+
* `Capability.policies`. Refused rather than dropped, since dropping a rule fails open too. */
|
|
980
|
+
function assertPoliciesInvariant(capability) {
|
|
981
|
+
if (capability.contract !== "invariant" && (capability.policies?.length ?? 0) > 0) {
|
|
982
|
+
throw new Error(`capability "${capability.name}" is detachable and may not contribute policies; declare it invariant`);
|
|
983
|
+
}
|
|
812
984
|
}
|
|
813
|
-
function safeCwd(
|
|
985
|
+
function safeCwd(environment) {
|
|
814
986
|
try {
|
|
815
|
-
return
|
|
987
|
+
return environment.getcwd();
|
|
816
988
|
}
|
|
817
989
|
catch {
|
|
818
990
|
return "";
|