@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.
Files changed (122) hide show
  1. package/CHANGELOG.md +115 -0
  2. package/dist/types/cli/append-system-prompt.d.ts +7 -0
  3. package/dist/types/cli/doctor/session-owners.d.ts +8 -2
  4. package/dist/types/cli/public-command-errors.d.ts +1 -0
  5. package/dist/types/cli/session-picker.d.ts +16 -3
  6. package/dist/types/cli/update-cli.d.ts +0 -2
  7. package/dist/types/cli-ordinary.d.ts +1 -1
  8. package/dist/types/commands/sdk.d.ts +2 -0
  9. package/dist/types/config/machine-identity.d.ts +11 -0
  10. package/dist/types/config/model-registry.d.ts +9 -0
  11. package/dist/types/config/settings-schema.d.ts +84 -4
  12. package/dist/types/lsp/client.d.ts +9 -0
  13. package/dist/types/lsp/types.d.ts +2 -0
  14. package/dist/types/main.d.ts +40 -3
  15. package/dist/types/modes/components/session-held-warning.d.ts +27 -0
  16. package/dist/types/modes/components/session-selector.d.ts +32 -1
  17. package/dist/types/modes/controllers/selector-controller.d.ts +8 -1
  18. package/dist/types/modes/interactive-mode.d.ts +12 -1
  19. package/dist/types/sdk/broker/broker.d.ts +3 -0
  20. package/dist/types/sdk/broker/lifecycle-ledger.d.ts +5 -2
  21. package/dist/types/sdk/broker/lifecycle.d.ts +2 -0
  22. package/dist/types/sdk/broker/session-index.d.ts +11 -0
  23. package/dist/types/sdk/bus/index.d.ts +1 -1
  24. package/dist/types/sdk/host/control/dispatch.d.ts +3 -0
  25. package/dist/types/sdk/host/registration-test-hold.d.ts +7 -0
  26. package/dist/types/sdk/index.d.ts +1 -0
  27. package/dist/types/sdk/lifecycle/service.d.ts +3 -0
  28. package/dist/types/sdk/session-api-key.d.ts +11 -4
  29. package/dist/types/sdk/session-readonly/format.d.ts +7 -0
  30. package/dist/types/sdk/session.d.ts +11 -0
  31. package/dist/types/sdk/startup-capability.d.ts +11 -2
  32. package/dist/types/session/agent-session.d.ts +1 -2
  33. package/dist/types/session/internal/managed-session-storage.d.ts +1 -1
  34. package/dist/types/session/internal/session-claim-set.d.ts +168 -13
  35. package/dist/types/session/session-handover.d.ts +62 -0
  36. package/dist/types/session/session-manager.d.ts +75 -15
  37. package/dist/types/session/session-owner-holder.d.ts +77 -0
  38. package/dist/types/session/session-ownership-mode.d.ts +45 -2
  39. package/dist/types/session/session-ownership.d.ts +25 -29
  40. package/dist/types/session/yield-queue.d.ts +13 -0
  41. package/dist/types/tools/bash.d.ts +7 -0
  42. package/dist/types/tools/browser/deferred-profile-cleanup.d.ts +3 -0
  43. package/dist/types/tools/browser/launch.d.ts +24 -1
  44. package/dist/types/tools/index.d.ts +6 -0
  45. package/dist/types/tools/output-meta.d.ts +17 -11
  46. package/dist/types/tools/tool-result.d.ts +1 -0
  47. package/package.json +9 -7
  48. package/scripts/compile-args.ts +6 -3
  49. package/scripts/run-acp-conformance.ts +36 -10
  50. package/scripts/verify-gjc-sdk-canonicalization.ts +2 -0
  51. package/src/cli/append-system-prompt.ts +34 -0
  52. package/src/cli/auth-broker-cli.ts +5 -1
  53. package/src/cli/doctor/session-owners.ts +8 -2
  54. package/src/cli/public-command-errors.ts +4 -0
  55. package/src/cli/session-picker.ts +57 -7
  56. package/src/cli/update-cli.ts +0 -22
  57. package/src/cli-ordinary.ts +2 -17
  58. package/src/commands/sdk.ts +37 -15
  59. package/src/config/machine-identity.ts +31 -2
  60. package/src/config/model-registry.ts +40 -6
  61. package/src/config/settings-schema.ts +50 -6
  62. package/src/config/settings.ts +65 -3
  63. package/src/gjc-runtime/launch-tmux.ts +4 -1
  64. package/src/internal-urls/docs-index.generated.ts +12 -12
  65. package/src/lsp/client.ts +60 -6
  66. package/src/lsp/index.ts +2 -6
  67. package/src/lsp/types.ts +2 -0
  68. package/src/main.ts +364 -93
  69. package/src/modes/DESIGN.md +36 -0
  70. package/src/modes/acp/acp-agent.ts +215 -31
  71. package/src/modes/components/session-held-warning.ts +62 -0
  72. package/src/modes/components/session-selector.ts +234 -11
  73. package/src/modes/controllers/goal-mode-controller.ts +14 -2
  74. package/src/modes/controllers/selector-controller.ts +192 -3
  75. package/src/modes/interactive-mode.ts +40 -2
  76. package/src/prompts/tools/bash.md +1 -1
  77. package/src/prompts/tools/monitor.md +1 -1
  78. package/src/runtime-mcp/manager.ts +5 -1
  79. package/src/sdk/acp/adapter.ts +2 -0
  80. package/src/sdk/broker/broker.ts +29 -2
  81. package/src/sdk/broker/lifecycle-ledger.ts +9 -7
  82. package/src/sdk/broker/lifecycle.ts +280 -39
  83. package/src/sdk/broker/session-index.ts +24 -0
  84. package/src/sdk/bus/index.ts +1 -0
  85. package/src/sdk/bus/lifecycle-commands.ts +4 -0
  86. package/src/sdk/cli/session-cli.ts +8 -0
  87. package/src/sdk/host/control/dispatch.ts +18 -0
  88. package/src/sdk/host/host.ts +5 -0
  89. package/src/sdk/host/registration-test-hold.ts +51 -0
  90. package/src/sdk/host/session-runtime.test.ts +42 -0
  91. package/src/sdk/index.ts +10 -0
  92. package/src/sdk/lifecycle/service.ts +33 -10
  93. package/src/sdk/prompt-failure.ts +4 -0
  94. package/src/sdk/protocol/operation-registry.ts +7 -1
  95. package/src/sdk/session-api-key.ts +31 -16
  96. package/src/sdk/session-readonly/format.ts +10 -0
  97. package/src/sdk/session-readonly/scope.ts +2 -1
  98. package/src/sdk/session.ts +60 -7
  99. package/src/sdk/startup-capability.ts +27 -2
  100. package/src/session/agent-session.ts +411 -58
  101. package/src/session/internal/managed-session-storage.ts +16 -2
  102. package/src/session/internal/session-claim-set.ts +527 -49
  103. package/src/session/session-handover.ts +283 -0
  104. package/src/session/session-manager.ts +907 -148
  105. package/src/session/session-owner-holder.ts +177 -0
  106. package/src/session/session-ownership-mode.ts +84 -12
  107. package/src/session/session-ownership.ts +115 -89
  108. package/src/session/yield-queue.ts +43 -0
  109. package/src/session-import/provider-service.ts +8 -0
  110. package/src/setup/provider-onboarding.ts +5 -5
  111. package/src/task/executor.ts +2 -0
  112. package/src/tools/bash.ts +10 -0
  113. package/src/tools/browser/deferred-profile-cleanup.ts +20 -0
  114. package/src/tools/browser/launch.ts +133 -14
  115. package/src/tools/browser/registry.ts +72 -19
  116. package/src/tools/index.ts +10 -1
  117. package/src/tools/monitor.ts +267 -29
  118. package/src/tools/output-meta.ts +61 -28
  119. package/src/tools/tool-catalog.generated.ts +2 -2
  120. package/src/tools/tool-result.ts +5 -0
  121. package/dist/types/cli/macos-community-app.d.ts +0 -41
  122. package/src/cli/macos-community-app.ts +0 -1449
@@ -0,0 +1,283 @@
1
+ /**
2
+ * Continue here (session single-owner design §12 "hand over to the TUI", §13 L1): a session held by
3
+ * a broker-launched host is closed through the broker, between turns, and claimed by this process,
4
+ * so this process becomes its one writer. Remote clients attached to the host (ACP bridges, chat
5
+ * daemons) re-attach to this process's endpoint through the broker; they never block the close.
6
+ */
7
+ import { randomUUID } from "node:crypto";
8
+ import { logger } from "@gajae-code/utils";
9
+ import { endpointIncarnation } from "../sdk/broker/endpoint-authority";
10
+ import { processIncarnation } from "../sdk/broker/process-incarnation";
11
+ import {
12
+ DIRECT_SESSION_REGISTRATION_ATTEMPTS,
13
+ type IndexedSession,
14
+ isTransientSessionIndexLockError,
15
+ resolveSessionLocator,
16
+ SessionIndex,
17
+ type SessionLocatorV2,
18
+ } from "../sdk/broker/session-index";
19
+ import { createBrokerSessionLifecycleService } from "../sdk/lifecycle/broker-client";
20
+ import { attemptSessionClaim, claimRefusal, type ResolvedSessionOwnership } from "./internal/session-claim-set";
21
+ import {
22
+ probeSessionOwner,
23
+ SessionHeldError,
24
+ type SessionOwnerClaim,
25
+ type SessionOwnerProbe,
26
+ type SessionOwnerSurface,
27
+ } from "./session-ownership";
28
+
29
+ /** The host Continue here closes: its index row's endpoint authority, and where remote clients look for it. */
30
+ export interface SessionHandoverTarget {
31
+ readonly sessionId: string;
32
+ readonly agentDir: string;
33
+ readonly cwd: string;
34
+ readonly endpointGeneration: number;
35
+ readonly endpointIncarnation: string;
36
+ }
37
+
38
+ /**
39
+ * `closed`: the host exited and this process holds the claim (`undefined` only when claims fail
40
+ * open); the caller keeps it until its own open or switch has claimed, then releases it.
41
+ */
42
+ export type SessionHandoverOutcome =
43
+ | { readonly kind: "closed"; readonly claim: SessionOwnerClaim | undefined }
44
+ | { readonly kind: "refused"; readonly message: string };
45
+
46
+ export const SESSION_HANDOVER_BUSY_MESSAGE = "The session is running a turn; try again when it finishes.";
47
+
48
+ const HANDOVER_ACTOR = { id: "gjc-continue-here", namespace: "session:handover" } as const;
49
+ /** This process's generation-0 index row for the session while it takes it over. */
50
+ interface FenceRow {
51
+ readonly sessionId: string;
52
+ readonly locator: SessionLocatorV2;
53
+ readonly endpointGeneration: 0;
54
+ readonly pid: number;
55
+ readonly processIncarnation?: string;
56
+ }
57
+ /** An idle close waits up to three bounded teardown windows (graceful, SIGTERM, SIGKILL) before it answers. */
58
+ const HANDOVER_CLOSE_TIMEOUT_MS = 30_000;
59
+ /**
60
+ * Holder surfaces a broker-launched host claims as. A host claims the session before its index row
61
+ * and endpoint are published, so for these the warning waits for the row before it decides.
62
+ */
63
+ const BROKER_HOST_SURFACES: ReadonlySet<SessionOwnerSurface> = new Set(["sdk-host", "acp-host"]);
64
+ /**
65
+ * Longest the warning waits for a host that holds the claim to publish its row. A UX cap below the
66
+ * host readiness budget (`DEFAULT_READINESS_TIMEOUT_MS`, 10 s); a host slower than this gets
67
+ * Fork/Cancel.
68
+ */
69
+ const HOST_PUBLICATION_WAIT_MS = 8_000;
70
+ const HOST_PUBLICATION_POLL_MS = 100;
71
+
72
+ export interface SessionHandoverWaitOptions {
73
+ /** Ends the wait at the next poll: the caller was cancelled or is exiting. */
74
+ readonly signal?: AbortSignal;
75
+ /** Called once, when the warning starts waiting for the host to publish. */
76
+ readonly onWaiting?: () => void;
77
+ }
78
+
79
+ /** The held-session warning's input for a refusal, as it stands after any wait. */
80
+ export interface SessionHandoverCheck {
81
+ /** Who to warn about now; `undefined` once nothing holds the session, so it opens as unheld. */
82
+ readonly error: SessionHeldError | undefined;
83
+ /** The host Continue here closes, when it is offered for `error`. */
84
+ readonly target: SessionHandoverTarget | undefined;
85
+ }
86
+
87
+ type HandoverLookup =
88
+ | { readonly kind: "found"; readonly target: SessionHandoverTarget }
89
+ | { readonly kind: "none" }
90
+ /** The holder let go during the wait; the probe says who holds the session now. */
91
+ | { readonly kind: "let-go"; readonly probe: SessionOwnerProbe };
92
+
93
+ const NO_TARGET: HandoverLookup = { kind: "none" };
94
+
95
+ /**
96
+ * Whether Continue here is offered for `error`, and for which host: the holder must be the live,
97
+ * broker-launched host in the session index (its row carries a `lifecycleRequestId`, design §13
98
+ * L1), not a terminal, the app or an embedding. The surface label in the holder record does not
99
+ * decide it.
100
+ *
101
+ * A host claims before it publishes (a remote resume that reached the broker first, design §13
102
+ * H3), so when the holder claimed as a host and its row is not there yet, this waits for the row,
103
+ * at most {@link HOST_PUBLICATION_WAIT_MS}, while that host still holds the session and has not
104
+ * published an endpoint. A holder that let go meanwhile is not warned about: a free session opens
105
+ * as unheld, and a new holder is looked up once, without waiting.
106
+ */
107
+ export async function checkSessionHandover(
108
+ error: SessionHeldError,
109
+ agentDir: string,
110
+ options: SessionHandoverWaitOptions = {},
111
+ ): Promise<SessionHandoverCheck> {
112
+ const waitMs = error.holder && BROKER_HOST_SURFACES.has(error.holder.surface) ? HOST_PUBLICATION_WAIT_MS : 0;
113
+ const looked = await lookUpHandoverTarget(error, agentDir, waitMs, options);
114
+ if (looked.kind === "found") return { error, target: looked.target };
115
+ if (looked.kind === "none") return { error, target: undefined };
116
+ const { probe } = looked;
117
+ if (probe.state === "free" || (probe.state === "held" && probe.self)) return { error: undefined, target: undefined };
118
+ if (probe.state !== "held") return { error, target: undefined };
119
+ const current = new SessionHeldError(error.sessionId, probe.holder);
120
+ const next = await lookUpHandoverTarget(current, agentDir, 0);
121
+ return { error: current, target: next.kind === "found" ? next.target : undefined };
122
+ }
123
+
124
+ async function lookUpHandoverTarget(
125
+ error: SessionHeldError,
126
+ agentDir: string,
127
+ waitMs: number,
128
+ options: SessionHandoverWaitOptions = {},
129
+ ): Promise<HandoverLookup> {
130
+ const holder = error.holder;
131
+ if (!holder || holder.host !== undefined) return NO_TARGET;
132
+ const deadline = Date.now() + waitMs;
133
+ try {
134
+ const index = new SessionIndex(agentDir);
135
+ await index.refresh();
136
+ let waiting = false;
137
+ for (;;) {
138
+ const rows = index
139
+ .listSessions(undefined, new Set([error.sessionId]))
140
+ .sessions.filter(row => row.sessionId === error.sessionId && row.live && row.pid === holder.pid);
141
+ const target = handoverTargetIn(rows, error.sessionId, agentDir);
142
+ if (target) return { kind: "found", target };
143
+ // A published endpoint without a lifecycle identity is not a launched host: nothing to wait for.
144
+ if (Date.now() >= deadline || options.signal?.aborted || rows.some(row => row.endpointGeneration > 0))
145
+ return NO_TARGET;
146
+ const probe = await probeSessionOwner(error.sessionId);
147
+ if (!(probe.state === "held" && !probe.self && probe.holder?.pid === holder.pid))
148
+ return { kind: "let-go", probe };
149
+ if (!waiting) {
150
+ waiting = true;
151
+ options.onWaiting?.();
152
+ }
153
+ await Bun.sleep(HOST_PUBLICATION_POLL_MS);
154
+ if (options.signal?.aborted) return NO_TARGET;
155
+ await index.refreshIfChanged();
156
+ }
157
+ } catch (failure) {
158
+ logger.warn("Could not read the session index for Continue here", { error: String(failure) });
159
+ return NO_TARGET;
160
+ }
161
+ }
162
+
163
+ function handoverTargetIn(
164
+ rows: readonly IndexedSession[],
165
+ sessionId: string,
166
+ agentDir: string,
167
+ ): SessionHandoverTarget | undefined {
168
+ for (const row of rows) {
169
+ if (row.lifecycleRequestId === undefined) continue;
170
+ const incarnation = endpointIncarnation(row, sessionId);
171
+ if (!incarnation) continue;
172
+ return {
173
+ sessionId,
174
+ agentDir,
175
+ cwd: row.locator.cwd,
176
+ endpointGeneration: row.endpointGeneration,
177
+ endpointIncarnation: incarnation,
178
+ };
179
+ }
180
+ return undefined;
181
+ }
182
+
183
+ /**
184
+ * Hand the session over to this process (design §13 L1):
185
+ * 1. A generation-0 row for this process fences the gap, so a remote resume after the host exits
186
+ * sees the session live and waits instead of launching another host.
187
+ * 2. The broker closes the host only between turns (`ifIdle`, atomic in the host); a running turn
188
+ * or work lease answers `busy`. It answers once the host process has exited.
189
+ * 3. This process claims the session. From here the broker's resume waits on the claim until this
190
+ * process publishes its endpoint, so the fence row is withdrawn on every outcome.
191
+ *
192
+ * The host is looked up again on every attempt, without waiting (the warning already waited for
193
+ * it), so a retry after `busy` uses its current endpoint authority; a host that has exited
194
+ * meanwhile leaves only the claim to take.
195
+ */
196
+ export async function handOverSession(
197
+ error: SessionHeldError,
198
+ agentDir: string,
199
+ ownership: ResolvedSessionOwnership,
200
+ ): Promise<SessionHandoverOutcome> {
201
+ const looked = await lookUpHandoverTarget(error, agentDir, 0);
202
+ if (looked.kind !== "found") return await claimHandedOver(error.sessionId, ownership);
203
+ const { target } = looked;
204
+ const index = new SessionIndex(agentDir);
205
+ const incarnation = processIncarnation(process.pid);
206
+ // Set before the append: an append can reject after its row is durable, so a row that was only
207
+ // attempted is withdrawn too.
208
+ let fence: FenceRow | undefined;
209
+ try {
210
+ fence = {
211
+ sessionId: target.sessionId,
212
+ locator: await resolveSessionLocator(target.cwd, agentDir),
213
+ endpointGeneration: 0,
214
+ pid: process.pid,
215
+ ...(incarnation ? { processIncarnation: incarnation } : {}),
216
+ };
217
+ await index.append({ type: "host_registered", ...fence });
218
+ } catch (failure) {
219
+ logger.warn("Continue here could not fence the session handover", { error: String(failure) });
220
+ if (fence) await withdrawFence(index, fence);
221
+ return { kind: "refused", message: "The session index could not be updated to hand the session over." };
222
+ }
223
+ try {
224
+ return (await closeIdleHost(target)) ?? (await claimHandedOver(target.sessionId, ownership));
225
+ } catch (failure) {
226
+ logger.warn("Continue here could not claim the session", { error: String(failure) });
227
+ return { kind: "refused", message: "The session host closed, but this terminal could not claim the session." };
228
+ } finally {
229
+ await withdrawFence(index, fence);
230
+ }
231
+ }
232
+
233
+ /** Withdraw the fence row, retrying lock contention as the direct-session registration does. */
234
+ async function withdrawFence(index: SessionIndex, fence: FenceRow): Promise<void> {
235
+ for (let attempt = 1; ; attempt++) {
236
+ try {
237
+ await index.append({ type: "host_unregistered", ...fence });
238
+ return;
239
+ } catch (failure) {
240
+ if (!isTransientSessionIndexLockError(failure) || attempt >= DIRECT_SESSION_REGISTRATION_ATTEMPTS) {
241
+ logger.warn("Could not withdraw the Continue here fence row", { error: String(failure) });
242
+ return;
243
+ }
244
+ await Bun.sleep(50 * attempt);
245
+ }
246
+ }
247
+ }
248
+
249
+ async function claimHandedOver(
250
+ sessionId: string,
251
+ ownership: ResolvedSessionOwnership,
252
+ ): Promise<SessionHandoverOutcome> {
253
+ // A cover for the open or switch that follows: that open's own claim releases it when it lands.
254
+ const attempt = await attemptSessionClaim(ownership, sessionId, undefined, { admission: true });
255
+ const refusal = claimRefusal(ownership, sessionId, attempt);
256
+ if (refusal) return { kind: "refused", message: refusal.operatorMessage };
257
+ return { kind: "closed", claim: attempt.status === "claimed" ? attempt.claim : undefined };
258
+ }
259
+
260
+ async function closeIdleHost(target: SessionHandoverTarget): Promise<SessionHandoverOutcome | undefined> {
261
+ try {
262
+ const outcome = await createBrokerSessionLifecycleService(target.agentDir).close({
263
+ actor: HANDOVER_ACTOR,
264
+ capability: "session.close",
265
+ // A fresh key per attempt: the broker replays a recorded refusal for a reused one.
266
+ requestKey: `continue-here:${target.sessionId}:${randomUUID()}`,
267
+ target: {
268
+ sessionId: target.sessionId,
269
+ endpointGeneration: target.endpointGeneration,
270
+ endpointIncarnation: target.endpointIncarnation,
271
+ ifIdle: true,
272
+ },
273
+ timeoutMs: HANDOVER_CLOSE_TIMEOUT_MS,
274
+ });
275
+ if (outcome.ok) return undefined;
276
+ if (outcome.error.code === "busy") return { kind: "refused", message: SESSION_HANDOVER_BUSY_MESSAGE };
277
+ logger.warn("Continue here: the broker did not close the session host", { code: outcome.error.code });
278
+ return { kind: "refused", message: `The session host could not be closed (${outcome.error.code}).` };
279
+ } catch (failure) {
280
+ logger.warn("Continue here: the session close request failed", { error: String(failure) });
281
+ return { kind: "refused", message: "The session host could not be reached to close it." };
282
+ }
283
+ }