@gajae-code/coding-agent 0.22.2 → 0.22.3
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/CHANGELOG.md +115 -0
- package/dist/types/cli/append-system-prompt.d.ts +7 -0
- package/dist/types/cli/doctor/session-owners.d.ts +8 -2
- package/dist/types/cli/public-command-errors.d.ts +1 -0
- package/dist/types/cli/session-picker.d.ts +16 -3
- package/dist/types/cli/update-cli.d.ts +0 -2
- package/dist/types/cli-ordinary.d.ts +1 -1
- package/dist/types/commands/sdk.d.ts +2 -0
- package/dist/types/config/machine-identity.d.ts +11 -0
- package/dist/types/config/model-registry.d.ts +9 -0
- package/dist/types/config/settings-schema.d.ts +84 -4
- package/dist/types/lsp/client.d.ts +9 -0
- package/dist/types/lsp/types.d.ts +2 -0
- package/dist/types/main.d.ts +40 -3
- package/dist/types/modes/components/session-held-warning.d.ts +27 -0
- package/dist/types/modes/components/session-selector.d.ts +32 -1
- package/dist/types/modes/controllers/selector-controller.d.ts +8 -1
- package/dist/types/modes/interactive-mode.d.ts +12 -1
- package/dist/types/sdk/broker/broker.d.ts +3 -0
- package/dist/types/sdk/broker/lifecycle-ledger.d.ts +5 -2
- package/dist/types/sdk/broker/lifecycle.d.ts +2 -0
- package/dist/types/sdk/broker/session-index.d.ts +11 -0
- package/dist/types/sdk/bus/index.d.ts +1 -1
- package/dist/types/sdk/host/control/dispatch.d.ts +3 -0
- package/dist/types/sdk/host/registration-test-hold.d.ts +7 -0
- package/dist/types/sdk/index.d.ts +1 -0
- package/dist/types/sdk/lifecycle/service.d.ts +3 -0
- package/dist/types/sdk/session-api-key.d.ts +11 -4
- package/dist/types/sdk/session-readonly/format.d.ts +7 -0
- package/dist/types/sdk/session.d.ts +11 -0
- package/dist/types/sdk/startup-capability.d.ts +11 -2
- package/dist/types/session/agent-session.d.ts +1 -2
- package/dist/types/session/internal/managed-session-storage.d.ts +1 -1
- package/dist/types/session/internal/session-claim-set.d.ts +168 -13
- package/dist/types/session/session-handover.d.ts +62 -0
- package/dist/types/session/session-manager.d.ts +75 -15
- package/dist/types/session/session-owner-holder.d.ts +77 -0
- package/dist/types/session/session-ownership-mode.d.ts +45 -2
- package/dist/types/session/session-ownership.d.ts +25 -29
- package/dist/types/session/yield-queue.d.ts +13 -0
- package/dist/types/tools/bash.d.ts +7 -0
- package/dist/types/tools/browser/deferred-profile-cleanup.d.ts +3 -0
- package/dist/types/tools/browser/launch.d.ts +24 -1
- package/dist/types/tools/index.d.ts +6 -0
- package/dist/types/tools/output-meta.d.ts +17 -11
- package/dist/types/tools/tool-result.d.ts +1 -0
- package/package.json +9 -7
- package/scripts/compile-args.ts +6 -3
- package/scripts/run-acp-conformance.ts +36 -10
- package/scripts/verify-gjc-sdk-canonicalization.ts +2 -0
- package/src/cli/append-system-prompt.ts +34 -0
- package/src/cli/auth-broker-cli.ts +5 -1
- package/src/cli/doctor/session-owners.ts +8 -2
- package/src/cli/public-command-errors.ts +4 -0
- package/src/cli/session-picker.ts +57 -7
- package/src/cli/update-cli.ts +0 -22
- package/src/cli-ordinary.ts +2 -17
- package/src/commands/sdk.ts +37 -15
- package/src/config/machine-identity.ts +31 -2
- package/src/config/model-registry.ts +40 -6
- package/src/config/settings-schema.ts +50 -6
- package/src/config/settings.ts +65 -3
- package/src/gjc-runtime/launch-tmux.ts +4 -1
- package/src/internal-urls/docs-index.generated.ts +12 -12
- package/src/lsp/client.ts +60 -6
- package/src/lsp/index.ts +2 -6
- package/src/lsp/types.ts +2 -0
- package/src/main.ts +364 -93
- package/src/modes/DESIGN.md +36 -0
- package/src/modes/acp/acp-agent.ts +215 -31
- package/src/modes/components/session-held-warning.ts +62 -0
- package/src/modes/components/session-selector.ts +234 -11
- package/src/modes/controllers/goal-mode-controller.ts +14 -2
- package/src/modes/controllers/selector-controller.ts +192 -3
- package/src/modes/interactive-mode.ts +40 -2
- package/src/prompts/tools/bash.md +1 -1
- package/src/prompts/tools/monitor.md +1 -1
- package/src/runtime-mcp/manager.ts +5 -1
- package/src/sdk/acp/adapter.ts +2 -0
- package/src/sdk/broker/broker.ts +29 -2
- package/src/sdk/broker/lifecycle-ledger.ts +9 -7
- package/src/sdk/broker/lifecycle.ts +280 -39
- package/src/sdk/broker/session-index.ts +24 -0
- package/src/sdk/bus/index.ts +1 -0
- package/src/sdk/bus/lifecycle-commands.ts +4 -0
- package/src/sdk/cli/session-cli.ts +8 -0
- package/src/sdk/host/control/dispatch.ts +18 -0
- package/src/sdk/host/host.ts +5 -0
- package/src/sdk/host/registration-test-hold.ts +51 -0
- package/src/sdk/host/session-runtime.test.ts +42 -0
- package/src/sdk/index.ts +10 -0
- package/src/sdk/lifecycle/service.ts +33 -10
- package/src/sdk/prompt-failure.ts +4 -0
- package/src/sdk/protocol/operation-registry.ts +7 -1
- package/src/sdk/session-api-key.ts +31 -16
- package/src/sdk/session-readonly/format.ts +10 -0
- package/src/sdk/session-readonly/scope.ts +2 -1
- package/src/sdk/session.ts +60 -7
- package/src/sdk/startup-capability.ts +27 -2
- package/src/session/agent-session.ts +411 -58
- package/src/session/internal/managed-session-storage.ts +16 -2
- package/src/session/internal/session-claim-set.ts +527 -49
- package/src/session/session-handover.ts +283 -0
- package/src/session/session-manager.ts +907 -148
- package/src/session/session-owner-holder.ts +177 -0
- package/src/session/session-ownership-mode.ts +84 -12
- package/src/session/session-ownership.ts +115 -89
- package/src/session/yield-queue.ts +43 -0
- package/src/session-import/provider-service.ts +8 -0
- package/src/setup/provider-onboarding.ts +5 -5
- package/src/task/executor.ts +2 -0
- package/src/tools/bash.ts +10 -0
- package/src/tools/browser/deferred-profile-cleanup.ts +20 -0
- package/src/tools/browser/launch.ts +133 -14
- package/src/tools/browser/registry.ts +72 -19
- package/src/tools/index.ts +10 -1
- package/src/tools/monitor.ts +267 -29
- package/src/tools/output-meta.ts +61 -28
- package/src/tools/tool-catalog.generated.ts +2 -2
- package/src/tools/tool-result.ts +5 -0
- package/dist/types/cli/macos-community-app.d.ts +0 -41
- package/src/cli/macos-community-app.ts +0 -1449
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Who holds a session, and how that is said: holder types, the held-session error and its text.
|
|
3
|
+
*
|
|
4
|
+
* Import-free on purpose. Machine entrypoints (ACP, MCP, the `gjc sdk session` CLI) and the broker's
|
|
5
|
+
* lifecycle service name a holder in their errors, and must not reach the claim and lock machinery in
|
|
6
|
+
* `session-ownership.ts` to do it (`scripts/verify-gjc-sdk-canonicalization.ts`).
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/** A session id that may be quoted in text; any other id may hold any text. */
|
|
10
|
+
export const SAFE_SESSION_ID = /^[A-Za-z0-9_-]{1,128}$/;
|
|
11
|
+
/** A host name that may be shown; any other host reads as "another gjc process". */
|
|
12
|
+
export const SAFE_SESSION_HOST = /^[A-Za-z0-9][A-Za-z0-9.-]{0,252}$/;
|
|
13
|
+
|
|
14
|
+
export const SESSION_OWNER_SURFACES = ["app", "terminal", "print", "sdk-host", "acp-host", "sdk"] as const;
|
|
15
|
+
export type SessionOwnerBaseSurface = (typeof SESSION_OWNER_SURFACES)[number];
|
|
16
|
+
/** Where the holder runs; a subagent child carries its parent's surface plus ` (subagent)`. */
|
|
17
|
+
export type SessionOwnerSurface = SessionOwnerBaseSurface | `${SessionOwnerBaseSurface} (subagent)`;
|
|
18
|
+
|
|
19
|
+
/** A verified holder: its lock is held, and (on this host) its pid and incarnation match its record. */
|
|
20
|
+
export interface SessionOwnerHolder {
|
|
21
|
+
readonly surface: SessionOwnerSurface;
|
|
22
|
+
readonly pid: number;
|
|
23
|
+
/** Present only when the holder runs on another host, whose pid cannot be checked here. */
|
|
24
|
+
readonly host?: string;
|
|
25
|
+
readonly gjcVersion?: string;
|
|
26
|
+
readonly claimedAt?: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function isSessionOwnerSurface(value: unknown): value is SessionOwnerSurface {
|
|
30
|
+
if (typeof value !== "string") return false;
|
|
31
|
+
const base = value.endsWith(" (subagent)") ? value.slice(0, -" (subagent)".length) : value;
|
|
32
|
+
return (SESSION_OWNER_SURFACES as readonly string[]).includes(base);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const SURFACE_NOUNS: Record<SessionOwnerBaseSurface, string> = {
|
|
36
|
+
app: "the Gajae Code app",
|
|
37
|
+
terminal: "another terminal",
|
|
38
|
+
print: "a gjc -p run",
|
|
39
|
+
"sdk-host": "an SDK session host",
|
|
40
|
+
"acp-host": "an ACP session host",
|
|
41
|
+
sdk: "an application using the gjc SDK",
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
/** The holder as a remote client is told it, in a broker lifecycle error: surface and pid only. */
|
|
45
|
+
export interface SessionOwnerHolderSummary {
|
|
46
|
+
readonly surface: SessionOwnerSurface;
|
|
47
|
+
readonly pid: number;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* {@link SessionOwnerHolderSummary} of `holder`, checked field by field because it may come from
|
|
52
|
+
* a file another process wrote; `undefined` when it does not name a surface and a positive pid.
|
|
53
|
+
* A holder on another host keeps its surface and pid; its host name stays out.
|
|
54
|
+
*/
|
|
55
|
+
export function sessionOwnerHolderSummary(holder: unknown): SessionOwnerHolderSummary | undefined {
|
|
56
|
+
if (typeof holder !== "object" || holder === null) return undefined;
|
|
57
|
+
const { surface, pid } = holder as { surface?: unknown; pid?: unknown };
|
|
58
|
+
return isSessionOwnerSurface(surface) && typeof pid === "number" && Number.isSafeInteger(pid) && pid > 0
|
|
59
|
+
? { surface, pid }
|
|
60
|
+
: undefined;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* How a holder is named to a person (design §3.4). The holder is checked again here, because a
|
|
65
|
+
* caller may build one: anything malformed reads as "another gjc process", never as raw text.
|
|
66
|
+
*/
|
|
67
|
+
export function sessionOwnerHolderPhrase(holder: SessionOwnerHolder | undefined): string {
|
|
68
|
+
if (!holder || !Number.isSafeInteger(holder.pid) || holder.pid <= 0 || !isSessionOwnerSurface(holder.surface))
|
|
69
|
+
return "another gjc process";
|
|
70
|
+
if (holder.host !== undefined)
|
|
71
|
+
return SAFE_SESSION_HOST.test(holder.host)
|
|
72
|
+
? `a gjc process on ${holder.host} (pid ${holder.pid})`
|
|
73
|
+
: "another gjc process";
|
|
74
|
+
const subagent = holder.surface.endsWith(" (subagent)");
|
|
75
|
+
const base = (subagent ? holder.surface.slice(0, -" (subagent)".length) : holder.surface) as SessionOwnerBaseSurface;
|
|
76
|
+
const noun = SURFACE_NOUNS[base];
|
|
77
|
+
return subagent ? `a subagent of ${noun} (pid ${holder.pid})` : `${noun} (pid ${holder.pid})`;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The holder as the SDK message names it (design §3.3): `terminal, pid 4242`, or `a gjc process on build-box, pid 4242` for a remote holder; `undefined` if unverified. */
|
|
81
|
+
function sessionOwnerHolderLabel(holder: SessionOwnerHolder | undefined): string | undefined {
|
|
82
|
+
if (!holder || !Number.isSafeInteger(holder.pid) || holder.pid <= 0 || !isSessionOwnerSurface(holder.surface))
|
|
83
|
+
return undefined;
|
|
84
|
+
if (holder.host === undefined) return `${holder.surface}, pid ${holder.pid}`;
|
|
85
|
+
return SAFE_SESSION_HOST.test(holder.host) ? `a gjc process on ${holder.host}, pid ${holder.pid}` : undefined;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* The CLI command that continues a held session in a copy (design §3.3), for the CLI's refusals
|
|
90
|
+
* only: the SDK's `operatorMessage` names no command. `undefined` for an id that is not a safe file
|
|
91
|
+
* name, since any other id may hold any text.
|
|
92
|
+
*/
|
|
93
|
+
export function sessionHeldForkCommand(
|
|
94
|
+
sessionId: string,
|
|
95
|
+
options: {
|
|
96
|
+
readonly print?: boolean;
|
|
97
|
+
/** The transcript path the session was named by, repeated so the command reads the same file. */
|
|
98
|
+
readonly source?: string;
|
|
99
|
+
/** The `--session-dir` the session was found in; an id resolves only there. */
|
|
100
|
+
readonly sessionDir?: string;
|
|
101
|
+
} = {},
|
|
102
|
+
): string | undefined {
|
|
103
|
+
if (!SAFE_SESSION_ID.test(sessionId)) return undefined;
|
|
104
|
+
const source = options.source === undefined ? sessionId : shellWord(options.source);
|
|
105
|
+
const sessionDir = options.sessionDir === undefined ? undefined : shellWord(options.sessionDir);
|
|
106
|
+
if (source === undefined || (options.sessionDir !== undefined && sessionDir === undefined)) return undefined;
|
|
107
|
+
const flags = sessionDir === undefined ? "" : `--session-dir ${sessionDir} `;
|
|
108
|
+
return options.print ? `gjc -p ${flags}--fork ${source} "<message>"` : `gjc ${flags}--fork ${source}`;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** One shell word for a path in a printed command; `undefined` for text no terminal should print. */
|
|
112
|
+
function shellWord(value: string): string | undefined {
|
|
113
|
+
if (value === "" || /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(value)) return undefined;
|
|
114
|
+
return /^[A-Za-z0-9._/:@%+=,-]+$/.test(value) && !value.startsWith("-")
|
|
115
|
+
? value
|
|
116
|
+
: `'${value.replaceAll("'", "'\\''")}'`;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* The terminal warning for a session another process holds (design §3.1; Fork and Cancel only, the
|
|
121
|
+
* read-only view and Take over are deferred). Fixed vocabulary, the holder's §3.4 phrase and a safe
|
|
122
|
+
* short id only: nothing a session or another process wrote reaches the screen.
|
|
123
|
+
*/
|
|
124
|
+
export function sessionHeldWarning(error: SessionHeldError): { readonly heading: string; readonly lines: string[] } {
|
|
125
|
+
const subject = SAFE_SESSION_ID.test(error.sessionId) ? `Session ${error.sessionId.slice(0, 8)}` : "This session";
|
|
126
|
+
return {
|
|
127
|
+
heading: "This session is open in another process",
|
|
128
|
+
lines: [
|
|
129
|
+
`${subject} is open for writing in ${sessionOwnerHolderPhrase(error.holder)}.`,
|
|
130
|
+
"Only one process can write a session at a time.",
|
|
131
|
+
],
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** What a launch or the TUI says after Fork (design §3.1). */
|
|
136
|
+
export function sessionHeldForkedNotice(error: SessionHeldError): string {
|
|
137
|
+
return `Forked into a new session. The original stays with ${sessionOwnerHolderPhrase(error.holder)}.`;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const SURFACE_MARKERS: Record<SessionOwnerBaseSurface, string> = {
|
|
141
|
+
app: "in app",
|
|
142
|
+
terminal: "in terminal",
|
|
143
|
+
print: "in gjc -p",
|
|
144
|
+
"sdk-host": "in session host",
|
|
145
|
+
"acp-host": "in session host",
|
|
146
|
+
sdk: "in SDK app",
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
/** The short marker a session list shows on a row another process holds (design §1 row 2): `in terminal`. */
|
|
150
|
+
export function sessionOwnerHolderMarker(holder: SessionOwnerHolder | undefined): string {
|
|
151
|
+
if (!holder || !isSessionOwnerSurface(holder.surface) || holder.host !== undefined) return "in use";
|
|
152
|
+
if (holder.surface.endsWith(" (subagent)")) return "in subagent";
|
|
153
|
+
return SURFACE_MARKERS[holder.surface as SessionOwnerBaseSurface];
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* A session another live process holds for writing. `message` is the stable machine code; the
|
|
158
|
+
* fixed, path-free `operatorMessage` is what a person sees.
|
|
159
|
+
*/
|
|
160
|
+
export class SessionHeldError extends Error {
|
|
161
|
+
readonly code = "session_held";
|
|
162
|
+
readonly sessionId: string;
|
|
163
|
+
readonly holder: SessionOwnerHolder | undefined;
|
|
164
|
+
readonly operatorMessage: string;
|
|
165
|
+
|
|
166
|
+
constructor(sessionId: string, holder?: SessionOwnerHolder) {
|
|
167
|
+
super("session_held");
|
|
168
|
+
this.name = "SessionHeldError";
|
|
169
|
+
this.sessionId = sessionId;
|
|
170
|
+
this.holder = holder;
|
|
171
|
+
// Only a safe id is quoted, shortened as the CLI shows it; any other id may hold any text.
|
|
172
|
+
const subject = SAFE_SESSION_ID.test(sessionId) ? `Session ${sessionId.slice(0, 8)}` : "This session";
|
|
173
|
+
const label = sessionOwnerHolderLabel(holder);
|
|
174
|
+
const where = label ? `another process (${label})` : "another gjc process";
|
|
175
|
+
this.operatorMessage = `${subject} is open for writing in ${where}. Only one process can write a session at a time.`;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
@@ -17,7 +17,12 @@ import { trustedCoordinatorEnv } from "../gjc-runtime/sidecar-bootstrap-env";
|
|
|
17
17
|
|
|
18
18
|
export const SESSION_OWNERSHIP_MODES = ["off", "observe", "enforce"] as const;
|
|
19
19
|
export type SessionOwnershipMode = (typeof SESSION_OWNERSHIP_MODES)[number];
|
|
20
|
-
|
|
20
|
+
/**
|
|
21
|
+
* The mode when the operator set none. It is the effective default: `Settings.getGlobal` returns no
|
|
22
|
+
* value for an unset key, so the resolver falls back to this, and the schema default only mirrors it
|
|
23
|
+
* for display (a test keeps the two equal).
|
|
24
|
+
*/
|
|
25
|
+
export const DEFAULT_SESSION_OWNERSHIP_MODE: SessionOwnershipMode = "enforce";
|
|
21
26
|
export const SESSION_OWNERSHIP_ENV = "GJC_SESSION_OWNERSHIP";
|
|
22
27
|
|
|
23
28
|
/** Test-only seams shared by the ownership modules. Code, not environment, so a project `.env` cannot reach them. */
|
|
@@ -86,6 +91,20 @@ export function trustedSessionOwnershipOverride(
|
|
|
86
91
|
return trustedCoordinatorEnv(SESSION_OWNERSHIP_ENV, env, snapshot);
|
|
87
92
|
}
|
|
88
93
|
|
|
94
|
+
/**
|
|
95
|
+
* Remove a project-supplied `GJC_SESSION_OWNERSHIP` from `env` before it reaches a child. A child in
|
|
96
|
+
* another directory (a `--tmux --worktree` launch runs `--no-env-file` there) checks provenance against
|
|
97
|
+
* that directory's `.env`, so it would trust this project's value. Called beside the `HERDR_BIN_PATH`
|
|
98
|
+
* drop, with the same startup snapshot.
|
|
99
|
+
*/
|
|
100
|
+
export function dropProjectSuppliedSessionOwnershipOverride(
|
|
101
|
+
env: NodeJS.ProcessEnv,
|
|
102
|
+
snapshot: ProjectEnvSnapshot,
|
|
103
|
+
): void {
|
|
104
|
+
if (env[SESSION_OWNERSHIP_ENV] === undefined) return;
|
|
105
|
+
if (trustedCoordinatorEnv(SESSION_OWNERSHIP_ENV, env, snapshot) === undefined) delete env[SESSION_OWNERSHIP_ENV];
|
|
106
|
+
}
|
|
107
|
+
|
|
89
108
|
/**
|
|
90
109
|
* Bun loads the project `.env` from the launch directory, so provenance is checked there. A launch
|
|
91
110
|
* directory that is already gone leaves no snapshot to check against, and the override is ignored.
|
|
@@ -146,31 +165,84 @@ export function sessionOwnershipOverrideWasRead(): boolean {
|
|
|
146
165
|
return cachedOverride !== undefined;
|
|
147
166
|
}
|
|
148
167
|
|
|
149
|
-
|
|
168
|
+
/** `fresh` asks for the value on disk now, past any cache, where the source has one. */
|
|
169
|
+
export type SessionOwnershipSettingSource = (options?: { readonly fresh?: boolean }) => unknown;
|
|
150
170
|
|
|
151
|
-
|
|
152
|
-
|
|
171
|
+
let settingSource: SessionOwnershipSettingSource | undefined;
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Settings supplies the operator's global `session.ownership.mode` value: the process settings, or,
|
|
175
|
+
* before `Settings.init`, the agent directory's config file. Without a source the default applies.
|
|
176
|
+
*/
|
|
177
|
+
export function setSessionOwnershipSettingSource(source: SessionOwnershipSettingSource | undefined): void {
|
|
153
178
|
settingSource = source;
|
|
154
179
|
}
|
|
155
180
|
|
|
181
|
+
function readSettingSource(options?: { readonly fresh?: boolean }): unknown {
|
|
182
|
+
try {
|
|
183
|
+
return settingSource?.(options);
|
|
184
|
+
} catch {
|
|
185
|
+
return undefined;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* The mode as the operator has it now, for a refusal decision (5a). A refusal needs `enforce` both
|
|
191
|
+
* here and in the mode its factory read, so this can only lower a decision: `gjc config set
|
|
192
|
+
* session.ownership.mode off` reaches a running process's next refusal. It rereads the operator's
|
|
193
|
+
* config file. Only an explicit lower value lowers it: a file that names no mode, or cannot be read
|
|
194
|
+
* (the source then reports no value), leaves the factory's decision as it was, and so does the
|
|
195
|
+
* environment override unless it lowers.
|
|
196
|
+
*/
|
|
197
|
+
export function liveSessionOwnershipMode(): SessionOwnershipMode {
|
|
198
|
+
const forced = sessionOwnershipTestHookSlot().mode;
|
|
199
|
+
if (forced !== undefined) return forced;
|
|
200
|
+
const configured = parseMode(readSettingSource({ fresh: true })) ?? "enforce";
|
|
201
|
+
if (configured === "off") return "off";
|
|
202
|
+
cachedOverride ??= readOverride();
|
|
203
|
+
return resolveSessionOwnershipMode(configured, cachedOverride.value);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const MODE_RANK: Readonly<Record<SessionOwnershipMode, number>> = { off: 0, observe: 1, enforce: 2 };
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* The mode for a decision a running process makes now: `processMode` (the mode its process or
|
|
210
|
+
* factory read), lowered by {@link liveSessionOwnershipMode}. Only an explicit lower value in the
|
|
211
|
+
* operator's config file (or a lowering environment override) lowers it, and nothing raises it, so
|
|
212
|
+
* `gjc config set session.ownership.mode off` reaches a running process's next decision.
|
|
213
|
+
*/
|
|
214
|
+
export function liveSessionOwnershipModeFor(
|
|
215
|
+
processMode: SessionOwnershipMode = sessionOwnershipMode(),
|
|
216
|
+
): SessionOwnershipMode {
|
|
217
|
+
if (processMode === "off") return "off";
|
|
218
|
+
const live = liveSessionOwnershipMode();
|
|
219
|
+
return MODE_RANK[live] < MODE_RANK[processMode] ? live : processMode;
|
|
220
|
+
}
|
|
221
|
+
|
|
156
222
|
/**
|
|
157
223
|
* The mode for this process now. With the setting `off` it returns before reading the environment,
|
|
158
224
|
* so `off` does no work beyond reading the setting.
|
|
159
225
|
*/
|
|
160
226
|
export function sessionOwnershipMode(): SessionOwnershipMode {
|
|
227
|
+
return sessionOwnershipModeFor(undefined);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* The mode for a `session.ownership.mode` value read from settings other than the global instance
|
|
232
|
+
* (a launch that opens its session before `Settings.init`, or a scoped load), with the same override.
|
|
233
|
+
* A missing or invalid value, as from settings that never loaded the operator's config file (an
|
|
234
|
+
* embedding's `Settings.isolated()`), falls back to the setting source, so the operator's `off` still
|
|
235
|
+
* applies. A valid explicit value wins.
|
|
236
|
+
*/
|
|
237
|
+
export function sessionOwnershipModeFor(setting: unknown): SessionOwnershipMode {
|
|
161
238
|
const forced = sessionOwnershipTestHookSlot().mode;
|
|
162
239
|
if (forced !== undefined) return forced;
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
setting = settingSource?.();
|
|
166
|
-
} catch {
|
|
167
|
-
setting = undefined;
|
|
168
|
-
}
|
|
169
|
-
const configured = resolveSessionOwnershipMode(setting, undefined);
|
|
240
|
+
const value = parseMode(setting) === undefined ? readSettingSource() : setting;
|
|
241
|
+
const configured = resolveSessionOwnershipMode(value, undefined);
|
|
170
242
|
// `off` is the kill switch: it returns before the environment is read at all.
|
|
171
243
|
if (configured === "off") return "off";
|
|
172
244
|
cachedOverride ??= readOverride();
|
|
173
|
-
const effective = resolveSessionOwnershipMode(
|
|
245
|
+
const effective = resolveSessionOwnershipMode(value, cachedOverride.value);
|
|
174
246
|
reportIgnoredOverride(cachedOverride, configured, effective);
|
|
175
247
|
return effective;
|
|
176
248
|
}
|
|
@@ -5,8 +5,9 @@
|
|
|
5
5
|
* (the native `FileLock`), so it ends when its holder exits, however it exits. A holder record
|
|
6
6
|
* beside it names the holder for warnings; the lock is the truth and the record only a label.
|
|
7
7
|
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
8
|
+
* The session factories claim through the claim set (`internal/session-claim-set.ts`). A held
|
|
9
|
+
* session is logged and counted; only under mode `enforce` does a factory refuse it, with
|
|
10
|
+
* {@link SessionHeldError} (`claimRefusal`).
|
|
10
11
|
*/
|
|
11
12
|
import { createHash, randomUUID } from "node:crypto";
|
|
12
13
|
import * as fs from "node:fs";
|
|
@@ -26,6 +27,14 @@ import { recordSessionOwnershipCounts } from "@gajae-code/stats/session-ownershi
|
|
|
26
27
|
import { getStatsDbPath, getTrustedHomeDir, isEnoent, logger } from "@gajae-code/utils";
|
|
27
28
|
import { VERSION } from "@gajae-code/utils/cli-metadata";
|
|
28
29
|
import { observeProcess, processIncarnation } from "../sdk/broker/process-incarnation";
|
|
30
|
+
import {
|
|
31
|
+
isSessionOwnerSurface as isSurface,
|
|
32
|
+
SAFE_SESSION_HOST as SAFE_HOST,
|
|
33
|
+
SAFE_SESSION_ID as SAFE_ID,
|
|
34
|
+
type SessionOwnerBaseSurface,
|
|
35
|
+
type SessionOwnerHolder,
|
|
36
|
+
type SessionOwnerSurface,
|
|
37
|
+
} from "./session-owner-holder";
|
|
29
38
|
import {
|
|
30
39
|
classifySessionOwnerEntry,
|
|
31
40
|
SESSION_OWNER_RECORD_SUFFIX,
|
|
@@ -42,6 +51,21 @@ import {
|
|
|
42
51
|
type RuntimeLockDirectory,
|
|
43
52
|
} from "./session-storage";
|
|
44
53
|
|
|
54
|
+
export {
|
|
55
|
+
SESSION_OWNER_SURFACES,
|
|
56
|
+
SessionHeldError,
|
|
57
|
+
type SessionOwnerBaseSurface,
|
|
58
|
+
type SessionOwnerHolder,
|
|
59
|
+
type SessionOwnerHolderSummary,
|
|
60
|
+
type SessionOwnerSurface,
|
|
61
|
+
sessionHeldForkCommand,
|
|
62
|
+
sessionHeldForkedNotice,
|
|
63
|
+
sessionHeldWarning,
|
|
64
|
+
sessionOwnerHolderMarker,
|
|
65
|
+
sessionOwnerHolderPhrase,
|
|
66
|
+
sessionOwnerHolderSummary,
|
|
67
|
+
} from "./session-owner-holder";
|
|
68
|
+
|
|
45
69
|
const SIDECAR_SUFFIX = SESSION_OWNER_SIDECAR_SUFFIX;
|
|
46
70
|
const RECORD_SUFFIX = SESSION_OWNER_RECORD_SUFFIX;
|
|
47
71
|
const RECORD_VERSION = 1;
|
|
@@ -49,29 +73,12 @@ const RECORD_MAX_BYTES = 4096;
|
|
|
49
73
|
/** Every native call answers within this budget, or reports `timed_out`. */
|
|
50
74
|
const NATIVE_BUDGET_MS = 2_000;
|
|
51
75
|
const PROBE_CONCURRENCY = 16;
|
|
52
|
-
const SAFE_ID = /^[A-Za-z0-9_-]{1,128}$/;
|
|
53
76
|
/** Keys must not differ only in case: macOS volumes are case-insensitive by default. */
|
|
54
77
|
const PLAIN_KEY = /^[a-z0-9_-]{1,128}$/;
|
|
55
|
-
const SAFE_HOST = /^[A-Za-z0-9][A-Za-z0-9.-]{0,252}$/;
|
|
56
78
|
const SAFE_VERSION = /^[0-9A-Za-z.+-]{1,64}$/;
|
|
57
79
|
/** A UTC instant as `Date#toISOString` writes it; anything else in a record is not shown. */
|
|
58
80
|
const ISO_INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/;
|
|
59
81
|
|
|
60
|
-
export const SESSION_OWNER_SURFACES = ["app", "terminal", "print", "sdk-host", "acp-host", "sdk"] as const;
|
|
61
|
-
export type SessionOwnerBaseSurface = (typeof SESSION_OWNER_SURFACES)[number];
|
|
62
|
-
/** Where the holder runs; a subagent child carries its parent's surface plus ` (subagent)`. */
|
|
63
|
-
export type SessionOwnerSurface = SessionOwnerBaseSurface | `${SessionOwnerBaseSurface} (subagent)`;
|
|
64
|
-
|
|
65
|
-
/** A verified holder: its lock is held, and (on this host) its pid and incarnation match its record. */
|
|
66
|
-
export interface SessionOwnerHolder {
|
|
67
|
-
readonly surface: SessionOwnerSurface;
|
|
68
|
-
readonly pid: number;
|
|
69
|
-
/** Present only when the holder runs on another host, whose pid cannot be checked here. */
|
|
70
|
-
readonly host?: string;
|
|
71
|
-
readonly gjcVersion?: string;
|
|
72
|
-
readonly claimedAt?: string;
|
|
73
|
-
}
|
|
74
|
-
|
|
75
82
|
export type SessionOwnerUnknownReason = "unavailable" | "timed_out" | "failed";
|
|
76
83
|
|
|
77
84
|
export type SessionOwnerProbe =
|
|
@@ -148,6 +155,24 @@ function directoryFailure(error: unknown): SessionOwnershipError {
|
|
|
148
155
|
return new SessionOwnershipError("owners_directory_unsafe", { cause: error });
|
|
149
156
|
}
|
|
150
157
|
|
|
158
|
+
// =============================================================================
|
|
159
|
+
// Process surface
|
|
160
|
+
// =============================================================================
|
|
161
|
+
|
|
162
|
+
let processSurface: SessionOwnerBaseSurface = "sdk";
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* The surface this process claims sessions as when a factory is not told one (design §1): the CLI
|
|
166
|
+
* sets it once at startup (`terminal`, `print`, `sdk-host`); an embedding keeps `sdk`.
|
|
167
|
+
*/
|
|
168
|
+
export function setSessionOwnerSurface(surface: SessionOwnerBaseSurface): void {
|
|
169
|
+
processSurface = surface;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export function sessionOwnerSurface(): SessionOwnerBaseSurface {
|
|
173
|
+
return processSurface;
|
|
174
|
+
}
|
|
175
|
+
|
|
151
176
|
// =============================================================================
|
|
152
177
|
// Key and directory
|
|
153
178
|
// =============================================================================
|
|
@@ -211,12 +236,6 @@ interface OwnerRecord {
|
|
|
211
236
|
readonly claimedAt: string;
|
|
212
237
|
}
|
|
213
238
|
|
|
214
|
-
function isSurface(value: unknown): value is SessionOwnerSurface {
|
|
215
|
-
if (typeof value !== "string") return false;
|
|
216
|
-
const base = value.endsWith(" (subagent)") ? value.slice(0, -" (subagent)".length) : value;
|
|
217
|
-
return (SESSION_OWNER_SURFACES as readonly string[]).includes(base);
|
|
218
|
-
}
|
|
219
|
-
|
|
220
239
|
function parseRecord(text: string): OwnerRecord | undefined {
|
|
221
240
|
let value: unknown;
|
|
222
241
|
try {
|
|
@@ -319,6 +338,11 @@ interface RegistryEntry {
|
|
|
319
338
|
readonly recordPath: string;
|
|
320
339
|
readonly lock: FileLock;
|
|
321
340
|
holders: number;
|
|
341
|
+
/**
|
|
342
|
+
* Admission claims among the holders: an open's or a switch's cover, kept only until the opener's
|
|
343
|
+
* own claim lands ({@link releaseSessionAdmissions}). Absent in a registry an older copy created.
|
|
344
|
+
*/
|
|
345
|
+
admissions?: Set<Claim>;
|
|
322
346
|
}
|
|
323
347
|
|
|
324
348
|
interface SessionOwnerRegistry {
|
|
@@ -326,8 +350,13 @@ interface SessionOwnerRegistry {
|
|
|
326
350
|
readonly entries: Map<string, RegistryEntry>;
|
|
327
351
|
/** Acquires in flight, so a second claim in this process waits instead of contending. */
|
|
328
352
|
readonly pending: Map<string, Promise<void>>;
|
|
329
|
-
/**
|
|
353
|
+
/**
|
|
354
|
+
* Set once a lock call reports `unavailable` (no usable lock on this platform): claims are off for
|
|
355
|
+
* this process. A timeout never sets it (design §2.7): it skips that one call.
|
|
356
|
+
*/
|
|
330
357
|
unavailable: string | undefined;
|
|
358
|
+
/** Why the latch above was set; an older copy of this module may still latch `timed_out` here. */
|
|
359
|
+
latchReason?: "unavailable" | "timed_out";
|
|
331
360
|
/** In-process event counts (design §2.9); added after v1 shipped, so a v1 registry may lack it. */
|
|
332
361
|
counters?: Map<SessionOwnershipCounter, number>;
|
|
333
362
|
/** Counts already written to the stats database, and whether the exit write is armed. */
|
|
@@ -354,6 +383,7 @@ function registry(): SessionOwnerRegistry {
|
|
|
354
383
|
export function resetSessionOwnershipForTests(): void {
|
|
355
384
|
const current = registry();
|
|
356
385
|
current.unavailable = undefined;
|
|
386
|
+
current.latchReason = undefined;
|
|
357
387
|
current.counters?.clear();
|
|
358
388
|
current.persisted?.counts.clear();
|
|
359
389
|
const leaked = [...current.entries.values()];
|
|
@@ -374,6 +404,8 @@ export const SESSION_OWNERSHIP_COUNTERS = [
|
|
|
374
404
|
"claim_conflict",
|
|
375
405
|
/** A claim skipped by the narrow fail-open policy (design §2.7). */
|
|
376
406
|
"fail_open",
|
|
407
|
+
/** A claim that would refuse the session in enforce (an owners-directory failure), only logged before then. */
|
|
408
|
+
"claim_failed",
|
|
377
409
|
/** Locks this process still held when it exited: a missed release. */
|
|
378
410
|
"held_at_exit",
|
|
379
411
|
"release_after_deferred_timeout",
|
|
@@ -449,21 +481,37 @@ function markUnavailable(code: string | undefined): string {
|
|
|
449
481
|
const latched = code ?? "unavailable";
|
|
450
482
|
if (current.unavailable === undefined) {
|
|
451
483
|
current.unavailable = latched;
|
|
484
|
+
current.latchReason = "unavailable";
|
|
452
485
|
logger.warn("Session ownership is unavailable; claims are off for this process", { code: latched });
|
|
453
486
|
}
|
|
454
487
|
return current.unavailable;
|
|
455
488
|
}
|
|
456
489
|
|
|
490
|
+
/** The fail-open a latched process returns for every later claim (`timed_out` only from an older copy). */
|
|
491
|
+
function latchedFailOpen(current: SessionOwnerRegistry): SessionOwnerClaimResult {
|
|
492
|
+
return failOpen(current.latchReason ?? "unavailable", current.unavailable);
|
|
493
|
+
}
|
|
494
|
+
|
|
457
495
|
class Claim implements SessionOwnerClaim {
|
|
458
496
|
readonly #sidecar: string;
|
|
459
497
|
readonly #entry: RegistryEntry;
|
|
460
498
|
readonly shared: boolean;
|
|
461
499
|
#released = false;
|
|
462
500
|
|
|
463
|
-
constructor(sidecar: string, entry: RegistryEntry, shared: boolean) {
|
|
501
|
+
constructor(sidecar: string, entry: RegistryEntry, shared: boolean, admission: boolean) {
|
|
464
502
|
this.#sidecar = sidecar;
|
|
465
503
|
this.#entry = entry;
|
|
466
504
|
this.shared = shared;
|
|
505
|
+
if (admission) {
|
|
506
|
+
entry.admissions ??= new Set();
|
|
507
|
+
entry.admissions.add(this);
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
/** Release every admission claim of this session except this claim, which keeps the lock. */
|
|
512
|
+
releaseAdmissions(): void {
|
|
513
|
+
if (this.#released) return;
|
|
514
|
+
for (const admission of [...(this.#entry.admissions ?? [])]) if (admission !== this) admission.release();
|
|
467
515
|
}
|
|
468
516
|
|
|
469
517
|
get sessionId(): string {
|
|
@@ -482,6 +530,7 @@ class Claim implements SessionOwnerClaim {
|
|
|
482
530
|
if (this.#released) return;
|
|
483
531
|
this.#released = true;
|
|
484
532
|
const entry = this.#entry;
|
|
533
|
+
entry.admissions?.delete(this);
|
|
485
534
|
entry.holders -= 1;
|
|
486
535
|
if (entry.holders > 0) return;
|
|
487
536
|
const entries = registry().entries;
|
|
@@ -503,6 +552,14 @@ class Claim implements SessionOwnerClaim {
|
|
|
503
552
|
}
|
|
504
553
|
}
|
|
505
554
|
|
|
555
|
+
/**
|
|
556
|
+
* `claim`, an opener's own claim of its session, has landed: release the admission claims that
|
|
557
|
+
* covered the open. `claim` is held, so the lock never lapses between them (design §2.5).
|
|
558
|
+
*/
|
|
559
|
+
export function releaseSessionAdmissions(claim: SessionOwnerClaim): void {
|
|
560
|
+
if (claim instanceof Claim) claim.releaseAdmissions();
|
|
561
|
+
}
|
|
562
|
+
|
|
506
563
|
function selfHolder(entry: RegistryEntry): SessionOwnerHolder {
|
|
507
564
|
return { surface: entry.surface, pid: process.pid, gjcVersion: VERSION, claimedAt: entry.claimedAt };
|
|
508
565
|
}
|
|
@@ -511,8 +568,12 @@ function selfHolder(entry: RegistryEntry): SessionOwnerHolder {
|
|
|
511
568
|
// Claim and probe
|
|
512
569
|
// =============================================================================
|
|
513
570
|
|
|
514
|
-
function failOpen(
|
|
515
|
-
|
|
571
|
+
function failOpen(
|
|
572
|
+
reason: "unavailable" | "timed_out",
|
|
573
|
+
code: string | undefined,
|
|
574
|
+
counted = true,
|
|
575
|
+
): SessionOwnerClaimResult {
|
|
576
|
+
if (counted) countSessionOwnershipEvent("fail_open");
|
|
516
577
|
return { status: "skipped", reason, code };
|
|
517
578
|
}
|
|
518
579
|
|
|
@@ -520,14 +581,27 @@ function failOpen(reason: "unavailable" | "timed_out", code: string | undefined)
|
|
|
520
581
|
* Claim `sessionId` for this process. A session this process already holds is shared (design D10).
|
|
521
582
|
* Throws `SessionOwnershipError` when the owners directory or the lock fails in a way that must
|
|
522
583
|
* refuse the session; only `unavailable` and `timed_out` fail open (design §2.7).
|
|
584
|
+
*
|
|
585
|
+
* `repeat` names the outcome the caller's previous attempt of this id had (a turn-start
|
|
586
|
+
* re-attempt): the same outcome again is neither counted nor logged again, so the counters count
|
|
587
|
+
* episodes, not turns.
|
|
588
|
+
*
|
|
589
|
+
* `admission` marks a cover an open or a switch takes before it reads the session: the opener's own
|
|
590
|
+
* claim releases it when it lands ({@link releaseSessionAdmissions}), so it is never a second holder
|
|
591
|
+
* once the session is open.
|
|
523
592
|
*/
|
|
524
593
|
export async function claimSessionOwner(
|
|
525
594
|
sessionId: string,
|
|
526
|
-
request: {
|
|
595
|
+
request: {
|
|
596
|
+
readonly surface: SessionOwnerSurface;
|
|
597
|
+
readonly repeat?: "held" | "timed_out";
|
|
598
|
+
readonly admission?: boolean;
|
|
599
|
+
},
|
|
527
600
|
): Promise<SessionOwnerClaimResult> {
|
|
601
|
+
const admission = request.admission === true;
|
|
528
602
|
const key = sessionOwnerKey(sessionId);
|
|
529
603
|
const current = registry();
|
|
530
|
-
if (current.unavailable !== undefined) return
|
|
604
|
+
if (current.unavailable !== undefined) return latchedFailOpen(current);
|
|
531
605
|
let directory: RuntimeLockDirectory;
|
|
532
606
|
try {
|
|
533
607
|
directory = prepareRuntimeLockDirectory("session-owners", trustedHome());
|
|
@@ -540,14 +614,14 @@ export async function claimSessionOwner(
|
|
|
540
614
|
const held = current.entries.get(sidecar);
|
|
541
615
|
if (held) {
|
|
542
616
|
held.holders += 1;
|
|
543
|
-
return { status: "claimed", claim: new Claim(sidecar, held, true) };
|
|
617
|
+
return { status: "claimed", claim: new Claim(sidecar, held, true, admission) };
|
|
544
618
|
}
|
|
545
619
|
const pending = current.pending.get(sidecar);
|
|
546
620
|
if (!pending) break;
|
|
547
621
|
await pending;
|
|
548
622
|
}
|
|
549
623
|
// The acquire waited on may have found the platform unavailable.
|
|
550
|
-
if (current.unavailable !== undefined) return
|
|
624
|
+
if (current.unavailable !== undefined) return latchedFailOpen(current);
|
|
551
625
|
const { promise, resolve } = Promise.withResolvers<void>();
|
|
552
626
|
current.pending.set(sidecar, promise);
|
|
553
627
|
try {
|
|
@@ -599,10 +673,10 @@ export async function claimSessionOwner(
|
|
|
599
673
|
}
|
|
600
674
|
current.entries.set(sidecar, entry);
|
|
601
675
|
countSessionOwnershipEvent("claim_taken");
|
|
602
|
-
return { status: "claimed", claim: new Claim(sidecar, entry, false) };
|
|
676
|
+
return { status: "claimed", claim: new Claim(sidecar, entry, false, admission) };
|
|
603
677
|
}
|
|
604
678
|
case FileLockAcquireStatus.Held:
|
|
605
|
-
countSessionOwnershipEvent("claim_conflict");
|
|
679
|
+
if (request.repeat !== "held") countSessionOwnershipEvent("claim_conflict");
|
|
606
680
|
return {
|
|
607
681
|
status: "held",
|
|
608
682
|
holder: verifiedHolder(readRecord(path.join(owners, `${key}${RECORD_SUFFIX}`)), sessionId),
|
|
@@ -610,9 +684,12 @@ export async function claimSessionOwner(
|
|
|
610
684
|
case FileLockAcquireStatus.Unavailable:
|
|
611
685
|
return failOpen("unavailable", markUnavailable(result.code));
|
|
612
686
|
case FileLockAcquireStatus.TimedOut:
|
|
613
|
-
// A stall
|
|
614
|
-
|
|
615
|
-
|
|
687
|
+
// A stall skips this call only (design §2.7): latching it would leave a long-lived writer
|
|
688
|
+
// unclaimed, and so invisible to other processes, for the rest of its life. Turn start
|
|
689
|
+
// re-attempts the current session, with backoff (`SessionClaimSet.reclaimCurrent`).
|
|
690
|
+
if (request.repeat !== "timed_out")
|
|
691
|
+
logger.warn("Session ownership claim timed out; this claim was skipped", { code: result.code });
|
|
692
|
+
return failOpen("timed_out", result.code ?? "timed_out", request.repeat !== "timed_out");
|
|
616
693
|
default:
|
|
617
694
|
throw new SessionOwnershipError(result.code ?? "lock_failed");
|
|
618
695
|
}
|
|
@@ -798,54 +875,3 @@ export async function inspectSessionOwners(
|
|
|
798
875
|
held.sort((a, b) => a.key.localeCompare(b.key));
|
|
799
876
|
return { directory: "present", ...counts, held };
|
|
800
877
|
}
|
|
801
|
-
|
|
802
|
-
// =============================================================================
|
|
803
|
-
// Refusal
|
|
804
|
-
// =============================================================================
|
|
805
|
-
|
|
806
|
-
const SURFACE_NOUNS: Record<SessionOwnerBaseSurface, string> = {
|
|
807
|
-
app: "the Gajae Code app",
|
|
808
|
-
terminal: "another terminal",
|
|
809
|
-
print: "a gjc -p run",
|
|
810
|
-
"sdk-host": "an SDK session host",
|
|
811
|
-
"acp-host": "an ACP session host",
|
|
812
|
-
sdk: "an application using the gjc SDK",
|
|
813
|
-
};
|
|
814
|
-
|
|
815
|
-
/**
|
|
816
|
-
* How a holder is named to a person (design §3.4). The holder is checked again here, because a
|
|
817
|
-
* caller may build one: anything malformed reads as "another gjc process", never as raw text.
|
|
818
|
-
*/
|
|
819
|
-
export function sessionOwnerHolderPhrase(holder: SessionOwnerHolder | undefined): string {
|
|
820
|
-
if (!holder || !Number.isSafeInteger(holder.pid) || holder.pid <= 0 || !isSurface(holder.surface))
|
|
821
|
-
return "another gjc process";
|
|
822
|
-
if (holder.host !== undefined)
|
|
823
|
-
return SAFE_HOST.test(holder.host)
|
|
824
|
-
? `a gjc process on ${holder.host} (pid ${holder.pid})`
|
|
825
|
-
: "another gjc process";
|
|
826
|
-
const subagent = holder.surface.endsWith(" (subagent)");
|
|
827
|
-
const base = (subagent ? holder.surface.slice(0, -" (subagent)".length) : holder.surface) as SessionOwnerBaseSurface;
|
|
828
|
-
const noun = SURFACE_NOUNS[base];
|
|
829
|
-
return subagent ? `a subagent of ${noun} (pid ${holder.pid})` : `${noun} (pid ${holder.pid})`;
|
|
830
|
-
}
|
|
831
|
-
|
|
832
|
-
/**
|
|
833
|
-
* A session another live process holds for writing. `message` is the stable machine code; the
|
|
834
|
-
* fixed, path-free `operatorMessage` is what a person sees.
|
|
835
|
-
*/
|
|
836
|
-
export class SessionHeldError extends Error {
|
|
837
|
-
readonly code = "session_held";
|
|
838
|
-
readonly sessionId: string;
|
|
839
|
-
readonly holder: SessionOwnerHolder | undefined;
|
|
840
|
-
readonly operatorMessage: string;
|
|
841
|
-
|
|
842
|
-
constructor(sessionId: string, holder?: SessionOwnerHolder) {
|
|
843
|
-
super("session_held");
|
|
844
|
-
this.name = "SessionHeldError";
|
|
845
|
-
this.sessionId = sessionId;
|
|
846
|
-
this.holder = holder;
|
|
847
|
-
// Only a safe id is quoted, shortened as the CLI shows it; any other id may hold any text.
|
|
848
|
-
const subject = SAFE_ID.test(sessionId) ? `Session ${sessionId.slice(0, 8)}` : "This session";
|
|
849
|
-
this.operatorMessage = `${subject} is open for writing in ${sessionOwnerHolderPhrase(holder)}. Only one process can write a session at a time. Close it there, or fork it to continue in a copy.`;
|
|
850
|
-
}
|
|
851
|
-
}
|