opencode-ahp 0.1.9 → 0.1.11
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/package.json +1 -1
- package/src/bridge.ts +50 -3
- package/src/host-base.ts +1 -1
- package/src/host-client-tools.ts +1 -1
- package/src/host-dispatch.ts +27 -1
- package/src/host-events.ts +26 -6
- package/src/host-rpc.ts +3 -0
- package/src/host-sessions.ts +65 -2
- package/src/host-terminals.ts +0 -1
- package/src/host-types.ts +8 -3
- package/src/index.ts +32 -4
- package/src/path-policy.ts +7 -4
package/package.json
CHANGED
package/src/bridge.ts
CHANGED
|
@@ -138,6 +138,15 @@ export interface FacadeSession {
|
|
|
138
138
|
model?: FacadeModelRef;
|
|
139
139
|
archived?: boolean;
|
|
140
140
|
time: { created: number; updated: number };
|
|
141
|
+
/**
|
|
142
|
+
* The opencode session this one is a child of — set only for
|
|
143
|
+
* subagent children (opencode core creates them with a `parentID`
|
|
144
|
+
* pointing at the caller's session). Root sessions and forks carry
|
|
145
|
+
* no parentID (a fork records its origin in `fork` instead). The
|
|
146
|
+
* host never surfaces a parented session as an AHP session
|
|
147
|
+
* (mirrors the TUI's session-list filter).
|
|
148
|
+
*/
|
|
149
|
+
parentID?: string;
|
|
141
150
|
/**
|
|
142
151
|
* Durable, core-opaque session metadata. The host uses
|
|
143
152
|
* one key — `opencode-ahp` — to make the peer-chat binding survive a
|
|
@@ -165,10 +174,31 @@ export type FacadePermissionDecision = "once" | "reject";
|
|
|
165
174
|
* wire shape; everything downstream works on this union.
|
|
166
175
|
*/
|
|
167
176
|
export type FacadeEvent =
|
|
168
|
-
| {
|
|
177
|
+
| {
|
|
178
|
+
type: "session.created";
|
|
179
|
+
sessionID: string;
|
|
180
|
+
title?: string;
|
|
181
|
+
agent?: string;
|
|
182
|
+
model?: FacadeModelRef;
|
|
183
|
+
/** The parent session id (subagent children); absent for root sessions and forks. */
|
|
184
|
+
parentID?: string;
|
|
185
|
+
}
|
|
169
186
|
| { type: "session.deleted"; sessionID: string }
|
|
170
187
|
| { type: "session.renamed"; sessionID: string; title: string }
|
|
171
|
-
| {
|
|
188
|
+
| {
|
|
189
|
+
type: "inbox.enqueued";
|
|
190
|
+
sessionID: string;
|
|
191
|
+
inboxID: string;
|
|
192
|
+
text: string;
|
|
193
|
+
delivery: FacadeDelivery | "default";
|
|
194
|
+
/**
|
|
195
|
+
* The enqueued item is a subagent completion report (a synthetic
|
|
196
|
+
* item whose `payload.metadata.source` is `"subagent"` — opencode
|
|
197
|
+
* core's report-back for an idle child). The host origins a
|
|
198
|
+
* report-driven turn as a system notification, not user input.
|
|
199
|
+
*/
|
|
200
|
+
subagent?: true;
|
|
201
|
+
}
|
|
172
202
|
| { type: "inbox.delivered"; sessionID: string; inboxID: string }
|
|
173
203
|
| { type: "execution.started"; sessionID: string }
|
|
174
204
|
| { type: "execution.succeeded"; sessionID: string }
|
|
@@ -815,6 +845,7 @@ export function mapV2EventRaw(raw: unknown): V2EventOutcome {
|
|
|
815
845
|
title: str(data["title"]),
|
|
816
846
|
agent: str(data["agent"]),
|
|
817
847
|
model: mapModelRef(data["model"]),
|
|
848
|
+
parentID: str(data["parentID"]),
|
|
818
849
|
},
|
|
819
850
|
};
|
|
820
851
|
case "session.deleted":
|
|
@@ -832,6 +863,12 @@ export function mapV2EventRaw(raw: unknown): V2EventOutcome {
|
|
|
832
863
|
if (inboxID === undefined || text === undefined)
|
|
833
864
|
return drop(missingOf({ inboxID, text }));
|
|
834
865
|
const delivery = str(data["delivery"]) ?? str(item?.["delivery"]);
|
|
866
|
+
// Subagent completion report: a SYNTHETIC item tagged
|
|
867
|
+
// `metadata.source: "subagent"` (opencode core's report-back for an
|
|
868
|
+
// idle child). The item type is part of the detection key — user
|
|
869
|
+
// items may carry arbitrary metadata too.
|
|
870
|
+
const metadata = payload !== undefined && isObj(payload["metadata"]) ? payload["metadata"] : undefined;
|
|
871
|
+
const subagent = item?.["type"] === "synthetic" && metadata !== undefined && metadata["source"] === "subagent";
|
|
835
872
|
return {
|
|
836
873
|
status: "ok",
|
|
837
874
|
event: {
|
|
@@ -840,6 +877,7 @@ export function mapV2EventRaw(raw: unknown): V2EventOutcome {
|
|
|
840
877
|
inboxID,
|
|
841
878
|
text,
|
|
842
879
|
delivery: delivery === "steer" || delivery === "queue" ? delivery : "default",
|
|
880
|
+
...(subagent ? { subagent: true as const } : {}),
|
|
843
881
|
},
|
|
844
882
|
};
|
|
845
883
|
}
|
|
@@ -1198,6 +1236,16 @@ export function userMessage(text: string, model?: string, agentUri?: string): Me
|
|
|
1198
1236
|
return message;
|
|
1199
1237
|
}
|
|
1200
1238
|
|
|
1239
|
+
/**
|
|
1240
|
+
* The system-notification-origin AHP `Message` for a machine-generated
|
|
1241
|
+
* turn input — a subagent completion report waking an idle parent
|
|
1242
|
+
* (design §8): the turn carries the report text verbatim, but its origin
|
|
1243
|
+
* is `systemNotification`, not user input.
|
|
1244
|
+
*/
|
|
1245
|
+
export function systemNotificationMessage(text: string): Message {
|
|
1246
|
+
return { text, origin: { kind: MessageKind.SystemNotification } };
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1201
1249
|
/** Bitmask covering the mutually-exclusive activity bits (bits 0–4). */
|
|
1202
1250
|
const STATUS_ACTIVITY_MASK = (1 << 5) - 1;
|
|
1203
1251
|
|
|
@@ -1383,7 +1431,6 @@ export function pastTenseMessageFor(toolName: string, inputText: string | undefi
|
|
|
1383
1431
|
* The "after" side of uncommitted/session changes is the live disk path
|
|
1384
1432
|
* itself (`file://`), read through `resourceRead` at view time.
|
|
1385
1433
|
*/
|
|
1386
|
-
const CONTENT_REF_PREFIX = "ahp-content://";
|
|
1387
1434
|
const CONTENT_HEAD_MARKER = "ahp-content://head/";
|
|
1388
1435
|
const CONTENT_SNAP_MARKER = "ahp-content://snap/";
|
|
1389
1436
|
|
package/src/host-base.ts
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
import { ActionType, ChangesetStatus, ActionEnvelope, ActionOrigin, ChatAction, ChatSummary, ChangesetAction, RootAction, SessionAction, SessionSummary, StateAction, TerminalAction } from "@microsoft/agent-host-protocol";
|
|
6
6
|
import { buildSessionSummary, chatSummaryOf, directoryUri, sessionSummaryStatus, type FacadeSession } from "./bridge.js";
|
|
7
|
-
import { ChannelRegistry, ChannelKind, ROOT_CHANNEL, channelKind, parseChangesetChannel
|
|
7
|
+
import { ChannelRegistry, ChannelKind, ROOT_CHANNEL, channelKind, parseChangesetChannel } from "./channels.js";
|
|
8
8
|
import { Sequencer } from "./seq.js";
|
|
9
9
|
import { createChangesetStateStore, createRootStateStore, ChangesetStateStore, RootStateStore } from "./state.js";
|
|
10
10
|
import { SocketState, ClientRecord, ChatRuntime, SessionRecord, TerminalRecord, HostOptions } from "./host-types.js";
|
package/src/host-client-tools.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
5
|
import { HostTurns } from "./host-turns.js";
|
|
6
|
-
import { ActionType, ResponsePartKind, ToolCallConfirmationReason, ToolCallStatus, SessionActiveClient,
|
|
6
|
+
import { ActionType, ResponsePartKind, ToolCallConfirmationReason, ToolCallStatus, SessionActiveClient, ToolCallConfirmationState, ToolCallState } from "@microsoft/agent-host-protocol";
|
|
7
7
|
import { invocationMessageFor, FacadeClientTool, FacadeClientToolResult } from "./bridge.js";
|
|
8
8
|
import { descriptionFor, findProvider, inputSchemaFor, toolUnion, ClientToolInvocation } from "./client-tools.js";
|
|
9
9
|
import { ChatRuntime, SessionRecord } from "./host-types.js";
|
package/src/host-dispatch.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
5
|
import { HostSessions } from "./host-sessions.js";
|
|
6
|
-
import { ActionType, SessionInputRequestKind,
|
|
6
|
+
import { ActionType, SessionInputRequestKind, ToolCallStatus, isClientDispatchable, ActionOrigin, ChatToolCallCompleteAction, ChatToolCallConfirmedAction, ChatToolCallContentChangedAction, ChatToolCallResultConfirmedAction, ChatTruncatedAction, ChatTurnCancelledAction, ChatTurnStartedAction, ChangesetFilesReviewChangedAction, Message, SessionActiveClient, SessionCustomizationToggledAction, SessionMcpServerStartRequestedAction, SessionMcpServerStopRequestedAction, SessionToolConfirmationRequest, StateAction, ToolCallResult } from "@microsoft/agent-host-protocol";
|
|
7
7
|
import { FacadeDelivery, MCP_CUSTOMIZATION_ID_PREFIX } from "./bridge.js";
|
|
8
8
|
import { normalizeToolDefinitions } from "./client-tools.js";
|
|
9
9
|
import { channelKind, parseChangesetChannel } from "./channels.js";
|
|
@@ -143,6 +143,10 @@ export class HostDispatch extends HostSessions {
|
|
|
143
143
|
if (chat === undefined) { noChat(); return; }
|
|
144
144
|
await this.dispatchTurnCancelled(chat, stateAction, origin);
|
|
145
145
|
return;
|
|
146
|
+
case ActionType.ChatTruncated:
|
|
147
|
+
if (chat === undefined) { noChat(); return; }
|
|
148
|
+
this.dispatchTruncated(chat, stateAction, origin);
|
|
149
|
+
return;
|
|
146
150
|
case ActionType.SessionTitleChanged:
|
|
147
151
|
await this.dispatchTitleChanged(rec, stateAction, origin);
|
|
148
152
|
return;
|
|
@@ -574,6 +578,28 @@ export class HostDispatch extends HostSessions {
|
|
|
574
578
|
await this.finishTurn(chat);
|
|
575
579
|
}
|
|
576
580
|
|
|
581
|
+
/**
|
|
582
|
+
* `chat/truncated` (client-dispatchable): the client trims the chat's
|
|
583
|
+
* turn history in the shared state (the documented use case: truncate,
|
|
584
|
+
* then dispatch a new `chat/turnStarted` with an edited message).
|
|
585
|
+
* State-only on this host — the official reducer trims the stored turns
|
|
586
|
+
* (to and including `turnId`, or to none when it is omitted) and drops
|
|
587
|
+
* the active turn (status → idle); opencode's message history has no
|
|
588
|
+
* counterpart and is untouched, and an in-flight execution is not
|
|
589
|
+
* interrupted: its late events land on a store that no longer carries
|
|
590
|
+
* the turn, and the reducer no-ops them. An unknown `turnId` follows
|
|
591
|
+
* the official reducer's no-op (accepted, state unchanged).
|
|
592
|
+
*/
|
|
593
|
+
private dispatchTruncated(chat: ChatRuntime, action: StateAction, origin: ActionOrigin | undefined): void {
|
|
594
|
+
const chatURI = chat.uri;
|
|
595
|
+
const a = action as ChatTruncatedAction;
|
|
596
|
+
if (a.turnId !== undefined && (typeof a.turnId !== "string" || a.turnId.length === 0)) {
|
|
597
|
+
this.echo(chatURI, action, origin, "invalid chat/truncated params (turnId must be a non-empty string)");
|
|
598
|
+
return;
|
|
599
|
+
}
|
|
600
|
+
this.echo(chatURI, action, origin);
|
|
601
|
+
}
|
|
602
|
+
|
|
577
603
|
/**
|
|
578
604
|
* `changeset/filesReviewChanged` (the only client-dispatchable changeset
|
|
579
605
|
* action): validate the channel resolves to a live store, then echo —
|
package/src/host-events.ts
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
import { HostDispatch } from "./host-dispatch.js";
|
|
6
6
|
import { ActionType, ResponsePartKind, SessionInputRequestKind, ToolCallContributorKind, ToolCallStatus, ErrorResponsePart, SessionToolClientExecutionRequest, SessionToolConfirmationRequest } from "@microsoft/agent-host-protocol";
|
|
7
|
-
import { displayNameFor, pastTenseMessageFor, userMessage, FacadeEvent } from "./bridge.js";
|
|
7
|
+
import { displayNameFor, pastTenseMessageFor, systemNotificationMessage, userMessage, FacadeEvent } from "./bridge.js";
|
|
8
8
|
import { EXTERNAL_REGISTER_GRACE_MS, errorMessage, mapToolResultContent } from "./host-util.js";
|
|
9
9
|
|
|
10
10
|
export class HostEvents extends HostDispatch {
|
|
@@ -42,6 +42,10 @@ export class HostEvents extends HostDispatch {
|
|
|
42
42
|
// ── opencode event pump handlers ───────────────────────────────────────
|
|
43
43
|
private async handleEvent(ev: FacadeEvent): Promise<void> {
|
|
44
44
|
if (ev.type === "session.created") {
|
|
45
|
+
// Subagent children (a `parentID` in the created event) never
|
|
46
|
+
// surface as AHP sessions — skip them before the deferral so no
|
|
47
|
+
// grace timer or existence fetch runs for them (design §7.2).
|
|
48
|
+
if (ev.parentID !== undefined) return;
|
|
45
49
|
// Every live chat has its own opencode session, so a
|
|
46
50
|
// created event for an already-bound id is ours (a createChat
|
|
47
51
|
// backend) and never an external session.
|
|
@@ -93,7 +97,11 @@ export class HostEvents extends HostDispatch {
|
|
|
93
97
|
}
|
|
94
98
|
return;
|
|
95
99
|
case "inbox.enqueued":
|
|
96
|
-
chat.lastInbox = {
|
|
100
|
+
chat.lastInbox = {
|
|
101
|
+
text: ev.text,
|
|
102
|
+
delivery: ev.delivery,
|
|
103
|
+
...(ev.subagent !== undefined ? { subagent: true } : {}),
|
|
104
|
+
};
|
|
97
105
|
return;
|
|
98
106
|
case "inbox.delivered":
|
|
99
107
|
// Steering consumption is handled at turn end (finishTurn).
|
|
@@ -101,8 +109,20 @@ export class HostEvents extends HostDispatch {
|
|
|
101
109
|
case "execution.started":
|
|
102
110
|
if (chat.currentTurnId !== null) return; // write-ahead already claimed the turn
|
|
103
111
|
// Orphan turn (an external TUI prompt, or a handoff this host did
|
|
104
|
-
// not initiate): start it with the last-seen inbox message.
|
|
105
|
-
|
|
112
|
+
// not initiate): start it with the last-seen inbox message. A
|
|
113
|
+
// subagent completion report waking an idle parent is
|
|
114
|
+
// machine-generated input, not a user prompt — the turn message
|
|
115
|
+
// carries the report text verbatim under a system-notification
|
|
116
|
+
// origin (design §8).
|
|
117
|
+
const inbox = chat.lastInbox;
|
|
118
|
+
this.startTurn(
|
|
119
|
+
chat,
|
|
120
|
+
inbox === null
|
|
121
|
+
? userMessage("")
|
|
122
|
+
: inbox.subagent
|
|
123
|
+
? systemNotificationMessage(inbox.text)
|
|
124
|
+
: userMessage(inbox.text),
|
|
125
|
+
);
|
|
106
126
|
return;
|
|
107
127
|
case "execution.succeeded":
|
|
108
128
|
if (chat.currentTurnId === null) return;
|
|
@@ -264,7 +284,7 @@ export class HostEvents extends HostDispatch {
|
|
|
264
284
|
// tool's terminal event (before the turn guard — a command that
|
|
265
285
|
// finishes after its turn was torn down still exits its
|
|
266
286
|
// terminal; no-op when the call never opened one).
|
|
267
|
-
this.finishTerminal(
|
|
287
|
+
this.finishTerminal(ev.id, { ok: true, content: ev.content });
|
|
268
288
|
if (chat.currentTurnId === null) return;
|
|
269
289
|
this.ensureToolReady(chat, ev.id, false);
|
|
270
290
|
if (this.toolCallTerminal(chat, ev.id)) {
|
|
@@ -293,7 +313,7 @@ export class HostEvents extends HostDispatch {
|
|
|
293
313
|
return;
|
|
294
314
|
}
|
|
295
315
|
case "tool.failed": {
|
|
296
|
-
this.finishTerminal(
|
|
316
|
+
this.finishTerminal(ev.id, { ok: false, message: ev.error.message });
|
|
297
317
|
if (chat.currentTurnId === null) return;
|
|
298
318
|
this.ensureToolReady(chat, ev.id, false);
|
|
299
319
|
if (this.toolCallTerminal(chat, ev.id)) {
|
package/src/host-rpc.ts
CHANGED
|
@@ -171,6 +171,9 @@ export class HostRpc extends HostEvents {
|
|
|
171
171
|
case "createSession":
|
|
172
172
|
await this.handleCreateSession(socketId, msg);
|
|
173
173
|
break;
|
|
174
|
+
case "disposeSession":
|
|
175
|
+
await this.handleDisposeSession(socketId, msg);
|
|
176
|
+
break;
|
|
174
177
|
case "createChat":
|
|
175
178
|
await this.handleCreateChat(socketId, msg);
|
|
176
179
|
break;
|
package/src/host-sessions.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Session section (design §7): `createSession`/`listSessions`/`resolveSessionConfig`, external session registration (TUI/restart resurfacing, AHP markers, peer-chat re-attach), and record removal.
|
|
2
|
+
* Session section (design §7): `createSession`/`disposeSession`/`listSessions`/`resolveSessionConfig`, external session registration (TUI/restart resurfacing, AHP markers, peer-chat re-attach), and record removal.
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
5
|
import { HostChats } from "./host-chats.js";
|
|
@@ -35,7 +35,7 @@ import { ROOT_CHANNEL, chatChannelURI, isSessionChannel, sessionChannelURI, sess
|
|
|
35
35
|
import { ERROR_INVALID_PARAMS } from "./handshake.js";
|
|
36
36
|
import { isRecord } from "./options.js";
|
|
37
37
|
import { createSessionStateStore } from "./state.js";
|
|
38
|
-
import { ERROR_INTERNAL, ERROR_NO_PROVIDER, ERROR_PERMISSION_DENIED, ERROR_SESSION_EXISTS } from "./host-errors.js";
|
|
38
|
+
import { ERROR_INTERNAL, ERROR_NO_PROVIDER, ERROR_PERMISSION_DENIED, ERROR_SESSION_EXISTS, ERROR_SESSION_NOT_FOUND } from "./host-errors.js";
|
|
39
39
|
import { RpcMessage, SessionRecord } from "./host-types.js";
|
|
40
40
|
import { EXTERNAL_REGISTER_GRACE_MS, AHP_METADATA_KEY, parseAhpMarker, errorMessage, firstEnabledModelRef, normalizeActiveClient } from "./host-util.js";
|
|
41
41
|
|
|
@@ -358,6 +358,58 @@ export class HostSessions extends HostChats {
|
|
|
358
358
|
this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: null });
|
|
359
359
|
}
|
|
360
360
|
|
|
361
|
+
/**
|
|
362
|
+
* `disposeSession` (AHP 1.0.0 session-channel command): dispose an AHP
|
|
363
|
+
* session and every opencode backend behind it — the default backend
|
|
364
|
+
* and each peer chat's backend. Result: `null`; the client's removal
|
|
365
|
+
* signal is the `root/sessionRemoved` notification `removeRecord`
|
|
366
|
+
* publishes (with the `root/activeSessionsChanged` count update),
|
|
367
|
+
* which always precedes the response. The channel is accepted in the
|
|
368
|
+
* same standard/legacy forms `createSession` echoes back, and an
|
|
369
|
+
* unknown channel answers -32001 (a channel that was a session but is
|
|
370
|
+
* already gone — e.g. disposed twice or deleted in the TUI first).
|
|
371
|
+
*
|
|
372
|
+
* The AHP-side unbind goes FIRST (the same race guard as
|
|
373
|
+
* `disposeChatBackend`): opencode's `session.deleted` event for each
|
|
374
|
+
* backend races this call through the event pump, and the pump's
|
|
375
|
+
* `byOpencode` guard must see the bindings already dropped — for the
|
|
376
|
+
* default backend a late binding would run `removeRecord` a second
|
|
377
|
+
* time (duplicate `root/sessionRemoved`), for a peer it would publish
|
|
378
|
+
* a `session/chatRemoved` for a chat whose record is already gone.
|
|
379
|
+
* `removeRecord` fires the peer backends' removals on the way (its
|
|
380
|
+
* standing behavior for the external-deletion path); the default
|
|
381
|
+
* backend is removed here, awaited, so a `listSessions` after the
|
|
382
|
+
* response does not resurface it lazily. R2: a failed backend removal
|
|
383
|
+
* still drops the AHP session — the lingering opencode session shows
|
|
384
|
+
* up in the TUI (and lazily in `listSessions`) until deleted there.
|
|
385
|
+
*/
|
|
386
|
+
protected async handleDisposeSession(socketId: number, msg: RpcMessage): Promise<void> {
|
|
387
|
+
const params = isRecord(msg.params) ? msg.params : {};
|
|
388
|
+
const channel = params["channel"];
|
|
389
|
+
if (typeof channel !== "string" || !isSessionChannel(channel)) {
|
|
390
|
+
this.sendError(
|
|
391
|
+
socketId,
|
|
392
|
+
msg.id,
|
|
393
|
+
ERROR_INVALID_PARAMS,
|
|
394
|
+
"disposeSession requires a session channel (ahp-session:/… or <provider>:/…)",
|
|
395
|
+
);
|
|
396
|
+
return;
|
|
397
|
+
}
|
|
398
|
+
const rec = this.byChannel.get(channel);
|
|
399
|
+
if (rec === undefined) {
|
|
400
|
+
this.sendError(socketId, msg.id, ERROR_SESSION_NOT_FOUND, `no such session: ${channel}`);
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
const defaultBackend = rec.sessionID;
|
|
404
|
+
this.removeRecord(rec);
|
|
405
|
+
try {
|
|
406
|
+
await this.opts.facade.removeSession(defaultBackend);
|
|
407
|
+
} catch (err) {
|
|
408
|
+
this.log(`failed to remove the session's opencode session ${defaultBackend}: ${errorMessage(err)}`);
|
|
409
|
+
}
|
|
410
|
+
this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: null });
|
|
411
|
+
}
|
|
412
|
+
|
|
361
413
|
/**
|
|
362
414
|
* `listSessions` (AHP 1.0.0 root command): all opencode sessions,
|
|
363
415
|
* most-recently-modified first, with in-memory cursor pagination.
|
|
@@ -513,6 +565,12 @@ export class HostSessions extends HostChats {
|
|
|
513
565
|
* client, or a session resurfacing after a restart).
|
|
514
566
|
* Outcomes:
|
|
515
567
|
*
|
|
568
|
+
* - the session has a parent (a subagent child — opencode core
|
|
569
|
+
* creates children with a `parentID`) → skip (undefined): children
|
|
570
|
+
* are internal to the parent's opencode session and never surface
|
|
571
|
+
* as AHP sessions (mirrors the TUI's parentID session-list filter;
|
|
572
|
+
* forks are not children — they carry no `parentID` — and register
|
|
573
|
+
* normally);
|
|
516
574
|
* - the opencode id already backs a chat of a live record → skip
|
|
517
575
|
* (undefined); `listSessions` must not surface peer-chat backends
|
|
518
576
|
* as their own AHP sessions;
|
|
@@ -529,6 +587,11 @@ export class HostSessions extends HostChats {
|
|
|
529
587
|
* opencode id (the record).
|
|
530
588
|
*/
|
|
531
589
|
private registerExternal(fs: FacadeSession): SessionRecord | undefined {
|
|
590
|
+
// Subagent children never surface (design §7.2): the single seam for
|
|
591
|
+
// every external-registration path (the event-pump deferral, the
|
|
592
|
+
// listSessions scan) — a skipped record gets no AHP session, no
|
|
593
|
+
// channel, and no root announcement.
|
|
594
|
+
if (fs.parentID !== undefined) return undefined;
|
|
532
595
|
const existing = this.sessions.get(fs.sessionID);
|
|
533
596
|
if (existing !== undefined) return existing;
|
|
534
597
|
if (this.byOpencode.has(fs.sessionID)) return undefined;
|
package/src/host-terminals.ts
CHANGED
|
@@ -603,7 +603,6 @@ export class HostTerminals extends HostResources {
|
|
|
603
603
|
* record itself is retained (retention); only the state moves on.
|
|
604
604
|
*/
|
|
605
605
|
protected finishTerminal(
|
|
606
|
-
chat: ChatRuntime,
|
|
607
606
|
toolCallId: string,
|
|
608
607
|
result: { ok: true; content: FacadeToolContent[] } | { ok: false; message: string },
|
|
609
608
|
): void {
|
package/src/host-types.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Record types shared by the host section classes: the per-socket, per-client, per-session, per-chat and per-terminal state shapes, and the HostOptions the Host is constructed with.
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
|
-
import {
|
|
5
|
+
import { Implementation } from "@microsoft/agent-host-protocol";
|
|
6
6
|
import { OpencodeFacade } from "./bridge.js";
|
|
7
7
|
import { ClientToolInvocation } from "./client-tools.js";
|
|
8
8
|
import { ChatStateStore, ChangesetStateStore, SessionStateStore, TerminalStateStore } from "./state.js";
|
|
@@ -70,8 +70,13 @@ export interface ChatRuntime {
|
|
|
70
70
|
* `tool.input.started`, removed at the opencode-side terminal).
|
|
71
71
|
*/
|
|
72
72
|
clientToolCalls: Map<string, ClientToolInvocation>;
|
|
73
|
-
/**
|
|
74
|
-
|
|
73
|
+
/**
|
|
74
|
+
* The most recent `session.inbox.enqueued` (external/TUI prompt
|
|
75
|
+
* tracking). `subagent` marks a synthetic completion report — a
|
|
76
|
+
* report-driven orphan turn originates its message as a system
|
|
77
|
+
* notification, not user input (design §8).
|
|
78
|
+
*/
|
|
79
|
+
lastInbox: { text: string; delivery: string; subagent?: true } | null;
|
|
75
80
|
// ── changesets ────────────────────────────────────────────────
|
|
76
81
|
/**
|
|
77
82
|
* Live chat-owned changeset stores (uncommitted + turn), keyed by
|
package/src/index.ts
CHANGED
|
@@ -253,6 +253,10 @@ function mapSessionInfo(info: SessionInfo): FacadeSession {
|
|
|
253
253
|
...(info.title !== undefined && info.title !== null ? { title: String(info.title) } : {}),
|
|
254
254
|
...(info.agent !== undefined ? { agent: String(info.agent) } : {}),
|
|
255
255
|
...(info.model !== undefined ? { model: modelRefOf(info) } : {}),
|
|
256
|
+
// Subagent children carry their parent's opencode session id; root
|
|
257
|
+
// sessions and forks (which record their origin in `fork`) do not.
|
|
258
|
+
// The host never surfaces a parented session (mirrors the TUI filter).
|
|
259
|
+
...(info.parentID !== undefined && info.parentID !== null ? { parentID: String(info.parentID) } : {}),
|
|
256
260
|
// SessionInfo.time carries `archived` only while archived.
|
|
257
261
|
...(info.time.archived !== undefined ? { archived: true } : {}),
|
|
258
262
|
// Durable, core-opaque metadata: the host reads its
|
|
@@ -1067,8 +1071,19 @@ export default Plugin.define({
|
|
|
1067
1071
|
cleanupHost = () => {
|
|
1068
1072
|
// Kill the pty terminals before the listener stops — their final
|
|
1069
1073
|
// terminal/exited actions still reach subscribers while it is up.
|
|
1070
|
-
|
|
1071
|
-
|
|
1074
|
+
// Per-step guards (design §13.4): a failing step is logged and
|
|
1075
|
+
// must not skip the later ones — skipping the pump abort leaves
|
|
1076
|
+
// the ctx.event.subscribe iteration running.
|
|
1077
|
+
try {
|
|
1078
|
+
host.stopTerminals();
|
|
1079
|
+
} catch (e) {
|
|
1080
|
+
console.error(`${TAG} location teardown: stopTerminals failed (${errorMessage(e)})`);
|
|
1081
|
+
}
|
|
1082
|
+
try {
|
|
1083
|
+
host.stopEventPump();
|
|
1084
|
+
} catch (e) {
|
|
1085
|
+
console.error(`${TAG} location teardown: stopEventPump failed (${errorMessage(e)})`);
|
|
1086
|
+
}
|
|
1072
1087
|
};
|
|
1073
1088
|
console.log(
|
|
1074
1089
|
`${TAG} AHP 1.0.0 host listening on ws${opts.tls ? "s" : ""}://${opts.host}:${listener.port}${opts.path} ` +
|
|
@@ -1076,7 +1091,11 @@ export default Plugin.define({
|
|
|
1076
1091
|
);
|
|
1077
1092
|
} catch (e) {
|
|
1078
1093
|
console.error(`${TAG} failed to start the AHP listener: ${errorMessage(e)}`);
|
|
1079
|
-
|
|
1094
|
+
try {
|
|
1095
|
+
listener?.stop();
|
|
1096
|
+
} catch (stopErr) {
|
|
1097
|
+
console.error(`${TAG} failed to stop the half-started AHP listener: ${errorMessage(stopErr)}`);
|
|
1098
|
+
}
|
|
1080
1099
|
listener = null;
|
|
1081
1100
|
return; // R2: the opencode server stays up without AHP
|
|
1082
1101
|
}
|
|
@@ -1084,10 +1103,19 @@ export default Plugin.define({
|
|
|
1084
1103
|
// 5. Cleanup: stop the pump (aborts the event subscription) and stop
|
|
1085
1104
|
// the listener, dropping every client connection. Logged because a
|
|
1086
1105
|
// torn-down listener with no log line is otherwise undiagnosable.
|
|
1106
|
+
// Teardown runs as a finalizer in the location's activation scope
|
|
1107
|
+
// (design §13.4): every step is individually guarded, and the
|
|
1108
|
+
// listener stop — the step that releases the port — runs
|
|
1109
|
+
// unconditionally and last, so an earlier failure can neither skip it
|
|
1110
|
+
// nor throw out of the finalizer.
|
|
1087
1111
|
return () => {
|
|
1088
1112
|
console.log(`${TAG} location teardown — stopping the AHP host (location unloaded by opencode)`);
|
|
1089
1113
|
cleanupHost?.();
|
|
1090
|
-
|
|
1114
|
+
try {
|
|
1115
|
+
listener?.stop();
|
|
1116
|
+
} catch (e) {
|
|
1117
|
+
console.error(`${TAG} location teardown: listener stop failed (${errorMessage(e)})`);
|
|
1118
|
+
}
|
|
1091
1119
|
};
|
|
1092
1120
|
},
|
|
1093
1121
|
});
|
package/src/path-policy.ts
CHANGED
|
@@ -31,10 +31,13 @@ export interface PathPolicyEnv {
|
|
|
31
31
|
* list is the unrestricted policy.
|
|
32
32
|
*/
|
|
33
33
|
export class PathPolicy {
|
|
34
|
-
private
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
) {
|
|
34
|
+
private readonly prefixes: readonly string[];
|
|
35
|
+
private readonly env?: PathPolicyEnv;
|
|
36
|
+
|
|
37
|
+
private constructor(prefixes: readonly string[], env?: PathPolicyEnv) {
|
|
38
|
+
this.prefixes = prefixes;
|
|
39
|
+
this.env = env;
|
|
40
|
+
}
|
|
38
41
|
|
|
39
42
|
/** No prefixes — every path is permitted. */
|
|
40
43
|
static unrestricted(): PathPolicy {
|