pi-ahp 0.0.0 → 0.1.0

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 (47) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +5 -39
  3. package/dist/bin/cli.js +54 -0
  4. package/dist/bin/tunnel.js +115 -0
  5. package/dist/channels/chat.js +105 -0
  6. package/dist/channels/root.js +30 -0
  7. package/dist/channels/session.js +90 -0
  8. package/dist/channels/terminal.js +9 -0
  9. package/dist/core/channels.js +87 -0
  10. package/dist/core/client-workarounds.js +188 -0
  11. package/dist/core/connection.js +24 -0
  12. package/dist/core/host.js +630 -0
  13. package/dist/core/sequencer.js +65 -0
  14. package/dist/core/state-store.js +118 -0
  15. package/dist/core/uri.js +28 -0
  16. package/dist/host/direct-settings.js +93 -0
  17. package/dist/host/pi-host.js +141 -0
  18. package/dist/host/serve.js +47 -0
  19. package/dist/host/terminal-service.js +293 -0
  20. package/dist/pi/activity.js +159 -0
  21. package/dist/pi/chat-driver.js +278 -0
  22. package/dist/pi/completions.js +134 -0
  23. package/dist/pi/delete-session.js +32 -0
  24. package/dist/pi/event-mapper.js +535 -0
  25. package/dist/pi/history.js +220 -0
  26. package/dist/pi/in-process-backend.js +109 -0
  27. package/dist/pi/message-input.js +139 -0
  28. package/dist/pi/models.js +92 -0
  29. package/dist/pi/project-trust.js +41 -0
  30. package/dist/pi/provider.js +9 -0
  31. package/dist/pi/resource-paths.js +76 -0
  32. package/dist/pi/resource-service.js +290 -0
  33. package/dist/pi/resource-watch-policy.js +29 -0
  34. package/dist/pi/resource-watch.js +302 -0
  35. package/dist/pi/session-catalogue.js +299 -0
  36. package/dist/pi/session-config.js +65 -0
  37. package/dist/pi/session-history.js +51 -0
  38. package/dist/pi/session-hydrator.js +128 -0
  39. package/dist/pi/session-registry.js +531 -0
  40. package/dist/pi/turn-paging.js +70 -0
  41. package/dist/protocol/errors.js +35 -0
  42. package/dist/protocol/jsonrpc.js +46 -0
  43. package/dist/protocol/version.js +32 -0
  44. package/dist/transport/websocket.js +101 -0
  45. package/dist/tunnel/devtunnel.js +127 -0
  46. package/dist/tunnel/vscode.js +31 -0
  47. package/package.json +66 -8
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Bang Lee
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,45 +1,11 @@
1
1
  # pi-ahp
2
2
 
3
- ## ⚠️ IMPORTANT NOTICE ⚠️
3
+ `pi-ahp` is an [Agent Host Protocol](https://github.com/microsoft/agent-host-protocol) host for the [pi coding agent](https://github.com/earendil-works/pi).
4
4
 
5
- **This package is created solely for the purpose of setting up OIDC (OpenID Connect) trusted publishing with npm.**
5
+ It embeds pi and makes its sessions available to AHP clients over WebSocket. Interoperability testing currently focuses on [Agent Host support in Visual Studio Code](https://code.visualstudio.com/docs/agents/concepts/agent-host), with [Agent Console](https://qusic.github.io/agent-console/) providing additional AHP client coverage. The host is not limited to either client.
6
6
 
7
- This is **NOT** a functional package and contains **NO** code or functionality beyond the OIDC setup configuration.
7
+ The project is currently under development and has not been released or distributed yet.
8
8
 
9
- ## Purpose
9
+ ## License
10
10
 
11
- This package exists to:
12
- 1. Configure OIDC trusted publishing for the package name `pi-ahp`
13
- 2. Enable secure, token-less publishing from CI/CD workflows
14
- 3. Establish provenance for packages published under this name
15
-
16
- ## What is OIDC Trusted Publishing?
17
-
18
- OIDC trusted publishing allows package maintainers to publish packages directly from their CI/CD workflows without needing to manage npm access tokens. Instead, it uses OpenID Connect to establish trust between the CI/CD provider (like GitHub Actions) and npm.
19
-
20
- ## Setup Instructions
21
-
22
- To properly configure OIDC trusted publishing for this package:
23
-
24
- 1. Go to [npmjs.com](https://www.npmjs.com/) and navigate to your package settings
25
- 2. Configure the trusted publisher (e.g., GitHub Actions)
26
- 3. Specify the repository and workflow that should be allowed to publish
27
- 4. Use the configured workflow to publish your actual package
28
-
29
- ## DO NOT USE THIS PACKAGE
30
-
31
- This package is a placeholder for OIDC configuration only. It:
32
- - Contains no executable code
33
- - Provides no functionality
34
- - Should not be installed as a dependency
35
- - Exists only for administrative purposes
36
-
37
- ## More Information
38
-
39
- For more details about npm's trusted publishing feature, see:
40
- - [npm Trusted Publishing Documentation](https://docs.npmjs.com/generating-provenance-statements)
41
- - [GitHub Actions OIDC Documentation](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/about-security-hardening-with-openid-connect)
42
-
43
- ---
44
-
45
- **Maintained for OIDC setup purposes only**
11
+ [MIT](LICENSE)
@@ -0,0 +1,54 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * `pi-ahp` — starts the host and prints the endpoint clients connect to.
4
+ */
5
+ import { loadDirectListenerSettings, SettingsError } from "../host/direct-settings.js";
6
+ import { closeOnSignal, startHost, VERSION } from "../host/serve.js";
7
+ function log(message) {
8
+ process.stderr.write(`${message}\n`);
9
+ }
10
+ function flagValue(args, flag) {
11
+ const index = args.indexOf(flag);
12
+ return index >= 0 ? args[index + 1] : undefined;
13
+ }
14
+ async function main() {
15
+ const args = process.argv.slice(2);
16
+ if (args.includes("--help") || args.includes("-h")) {
17
+ log([
18
+ `pi-ahp v${VERSION}`,
19
+ "",
20
+ "Usage: pi-ahp [--port <n>] [--host <addr>] [--cwd <path>] [--verbose]",
21
+ "",
22
+ "Direct-listener settings persist at ~/.pi/ahp/settings.json; the",
23
+ "port and token are generated on first run.",
24
+ ].join("\n"));
25
+ return;
26
+ }
27
+ const verbose = args.includes("--verbose");
28
+ const settings = await loadDirectListenerSettings();
29
+ const workingDirectory = flagValue(args, "--cwd") ?? process.cwd();
30
+ const server = await startHost({
31
+ host: flagValue(args, "--host") ?? settings.host,
32
+ port: Number(flagValue(args, "--port") ?? settings.port),
33
+ connectionToken: settings.token ?? undefined,
34
+ workingDirectory,
35
+ ...(verbose ? { log } : {}),
36
+ });
37
+ log(settings.token
38
+ ? `pi-ahp listening on ws://${server.host}:${server.port}?token=${settings.token}`
39
+ : `pi-ahp listening on ws://${server.host}:${server.port} (no token — anyone who can reach ${server.host} can drive the agent)`);
40
+ log(`working directory: ${workingDirectory}`);
41
+ closeOnSignal(server);
42
+ }
43
+ try {
44
+ await main();
45
+ }
46
+ catch (error) {
47
+ // A settings problem is the user's to fix, not a crash: print what is wrong
48
+ // and where, without a stack trace pointing into the store.
49
+ if (error instanceof SettingsError) {
50
+ process.stderr.write(`pi-ahp: ${error.message}\n`);
51
+ process.exit(1);
52
+ }
53
+ throw error;
54
+ }
@@ -0,0 +1,115 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Serves pi-ahp in the fixed Dev Tunnel shape VS Code discovers. Dev Tunnels
4
+ * controls remote access; the forwarded loopback listener has no URL token.
5
+ */
6
+ import { spawn } from "node:child_process";
7
+ import { startHost, VERSION } from "../host/serve.js";
8
+ import { createTunnel, ensurePort, findTunnel, rename, requireLogin, TunnelError } from "../tunnel/devtunnel.js";
9
+ import { displayLabel, nameLabel, TUNNEL_PORT } from "../tunnel/vscode.js";
10
+ function log(message) {
11
+ process.stderr.write(`${message}\n`);
12
+ }
13
+ async function main() {
14
+ const args = process.argv.slice(2);
15
+ if (args.includes("--help") || args.includes("-h")) {
16
+ log([
17
+ `pi-ahp-tunnel v${VERSION}`,
18
+ "",
19
+ "Usage: pi-ahp-tunnel [--name <label>] [--cwd <path>] [--verbose]",
20
+ "",
21
+ "Reuses this host's tunnel, creating one on the first run. `--name`",
22
+ "sets what VS Code shows in its list; without it, a name given here",
23
+ "or in VS Code earlier is left alone.",
24
+ "",
25
+ "Serves the host over a dev tunnel that VS Code discovers. Needs a",
26
+ "`devtunnel` on PATH, already logged in:",
27
+ "",
28
+ " devtunnel user login -g GitHub account",
29
+ " devtunnel user login Microsoft account (the default)",
30
+ "",
31
+ "Add -d for device-code auth when there is no browser. See",
32
+ "`devtunnel user login --help` for the rest.",
33
+ "",
34
+ "Does not read or modify pi-ahp's direct-listener settings. The",
35
+ `port is fixed by VS Code (${TUNNEL_PORT}); remote access is controlled`,
36
+ "by Microsoft Dev Tunnels rather than an additional URL token.",
37
+ ].join("\n"));
38
+ return;
39
+ }
40
+ const flag = (name) => {
41
+ const index = args.indexOf(name);
42
+ return index >= 0 ? args[index + 1] : undefined;
43
+ };
44
+ const verbose = args.includes("--verbose");
45
+ const workingDirectory = flag("--cwd") ?? process.cwd();
46
+ requireLogin();
47
+ const requested = flag("--name");
48
+ const name = requested ? nameLabel(requested) : undefined;
49
+ if (requested && !name) {
50
+ log(`ignoring --name ${requested}: nothing left after removing characters a label cannot hold`);
51
+ }
52
+ const existing = findTunnel();
53
+ let qualifiedId;
54
+ if (existing) {
55
+ qualifiedId = existing.tunnelId;
56
+ const current = displayLabel(existing.labels);
57
+ if (name && name !== current) {
58
+ rename(qualifiedId, current, name);
59
+ }
60
+ log(`tunnel: ${qualifiedId} (reused${name && name !== current ? `, renamed to ${name}` : ""})`);
61
+ }
62
+ else {
63
+ qualifiedId = createTunnel(name);
64
+ log(`tunnel: ${qualifiedId} (new${name ? `, named ${name}` : ""})`);
65
+ }
66
+ ensurePort(qualifiedId);
67
+ // The host must be up before the tunnel forwards to it, or the first client
68
+ // through the relay hits a closed port.
69
+ const server = await startHost({
70
+ host: "127.0.0.1",
71
+ port: TUNNEL_PORT,
72
+ workingDirectory,
73
+ ...(verbose ? { log } : {}),
74
+ });
75
+ log(`listening on 127.0.0.1:${server.port}, working directory: ${workingDirectory}`);
76
+ log("remote access control: Microsoft Dev Tunnels; local listener: no URL token");
77
+ const host = spawn("devtunnel", ["host", qualifiedId], { stdio: "inherit" });
78
+ let stopping = false;
79
+ // Shutting down goes through the child's `exit`, not alongside it. Killing
80
+ // the child and exiting in the same tick raced: `devtunnel host` outlives
81
+ // us, keeps the relay connection, and the tunnel looks hosted by a process
82
+ // that is gone.
83
+ host.on("exit", (code) => {
84
+ if (!stopping) {
85
+ log(`devtunnel host exited (${code}); shutting down`);
86
+ }
87
+ void server.close().then(() => process.exit(stopping ? 0 : (code ?? 1)));
88
+ });
89
+ const stop = () => {
90
+ if (stopping) {
91
+ // A second Ctrl-C means the wait itself is the problem.
92
+ process.exit(1);
93
+ }
94
+ stopping = true;
95
+ host.kill();
96
+ // A child that will not take SIGTERM should not wedge the terminal;
97
+ // an orphaned relay is the lesser failure.
98
+ setTimeout(() => host.kill("SIGKILL"), 5000).unref();
99
+ };
100
+ process.on("SIGINT", stop);
101
+ process.on("SIGTERM", stop);
102
+ log("");
103
+ log("In VS Code, enable `chat.remoteAgentHostsEnabled` and sign in to the");
104
+ log("same account; the tunnel appears in the agent host list.");
105
+ }
106
+ try {
107
+ await main();
108
+ }
109
+ catch (error) {
110
+ if (error instanceof TunnelError) {
111
+ process.stderr.write(`pi-ahp-tunnel: ${error.message}\n`);
112
+ process.exit(1);
113
+ }
114
+ throw error;
115
+ }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * The chat channel — `ahp-chat:/<uuid>`.
3
+ *
4
+ * Every session this host serves has exactly one chat. That is why the agent
5
+ * declares no `multipleChats` capability: its absence is the protocol's way of
6
+ * telling a client not to call `createChat`.
7
+ *
8
+ * @see https://microsoft.github.io/agent-host-protocol/specification/chat-channel
9
+ */
10
+ import { ActionType, ChatOriginKind, MessageKind, SessionStatus, } from "@microsoft/agent-host-protocol";
11
+ import { chatUri } from "../core/channels.js";
12
+ export function initialChatState(uri, title, selection) {
13
+ return {
14
+ resource: uri,
15
+ title,
16
+ status: SessionStatus.Idle,
17
+ modifiedAt: new Date().toISOString(),
18
+ // A session's default chat exists because the user made the session.
19
+ origin: { kind: ChatOriginKind.User },
20
+ turns: [],
21
+ // Seeded before the agent exists. Starting one takes seconds, and a
22
+ // client that subscribes in the meantime would otherwise find an empty
23
+ // model picker and be unable to send. The backend refines this once it
24
+ // is up, if it resolves to something different.
25
+ ...(selection ? { draft: { text: "", origin: { kind: MessageKind.User }, model: selection } } : {}),
26
+ };
27
+ }
28
+ export function chatSummaryOf(state) {
29
+ return {
30
+ resource: state.resource,
31
+ title: state.title,
32
+ status: state.status,
33
+ modifiedAt: state.modifiedAt,
34
+ ...(state.activity !== undefined ? { activity: state.activity } : {}),
35
+ ...(state.origin !== undefined ? { origin: state.origin } : {}),
36
+ ...(state.interactivity !== undefined ? { interactivity: state.interactivity } : {}),
37
+ ...(state.workingDirectories !== undefined ? { workingDirectories: state.workingDirectories } : {}),
38
+ };
39
+ }
40
+ /**
41
+ * Creates a session's default chat and registers it in the session catalog.
42
+ *
43
+ * The chat id is derived from the session id so that the pairing is
44
+ * reconstructible without a lookup table, matching how the session URI already
45
+ * carries pi's session id.
46
+ */
47
+ export function installDefaultChat(host, sessionChannel, sessionId, title, selection) {
48
+ const uri = chatUri(sessionId);
49
+ host.store.create(uri, initialChatState(uri, title, selection));
50
+ const summary = chatSummaryOf(host.store.get(uri));
51
+ host.dispatchServerAction(sessionChannel, { type: ActionType.SessionChatAdded, summary });
52
+ host.dispatchServerAction(sessionChannel, { type: ActionType.SessionDefaultChatChanged, defaultChat: uri });
53
+ return uri;
54
+ }
55
+ function equalUris(left, right) {
56
+ if (!left || !right) {
57
+ return left === right;
58
+ }
59
+ return left.length === right.length && left.every((uri, index) => uri === right[index]);
60
+ }
61
+ function equalSummary(left, right) {
62
+ return (left.resource === right.resource &&
63
+ left.title === right.title &&
64
+ left.status === right.status &&
65
+ left.activity === right.activity &&
66
+ left.modifiedAt === right.modifiedAt &&
67
+ (left.origin === right.origin || JSON.stringify(left.origin) === JSON.stringify(right.origin)) &&
68
+ left.interactivity === right.interactivity &&
69
+ equalUris(left.workingDirectories, right.workingDirectories));
70
+ }
71
+ /**
72
+ * Mirrors a chat's denormalized summary fields into its owning session.
73
+ *
74
+ * Partial updates cannot express removal of an optional JSON field: an
75
+ * `undefined` value disappears on the wire and means "unchanged". Use the
76
+ * action's full-summary upsert form when one of those fields is cleared.
77
+ */
78
+ export function syncChatSummary(host, sessionChannel, chatChannel) {
79
+ const chat = host.store.get(chatChannel);
80
+ const session = host.store.get(sessionChannel);
81
+ const previous = session?.chats.find((summary) => summary.resource === chatChannel);
82
+ if (!chat || !previous) {
83
+ return false;
84
+ }
85
+ const current = chatSummaryOf(chat);
86
+ if (equalSummary(previous, current)) {
87
+ return false;
88
+ }
89
+ const clearsOptional = (previous.activity !== undefined && current.activity === undefined) ||
90
+ (previous.origin !== undefined && current.origin === undefined) ||
91
+ (previous.interactivity !== undefined && current.interactivity === undefined) ||
92
+ (previous.workingDirectories !== undefined && current.workingDirectories === undefined);
93
+ if (clearsOptional) {
94
+ host.dispatchServerAction(sessionChannel, { type: ActionType.SessionChatAdded, summary: current });
95
+ }
96
+ else {
97
+ const { resource: _resource, ...changes } = current;
98
+ host.dispatchServerAction(sessionChannel, {
99
+ type: ActionType.SessionChatUpdated,
100
+ chat: chatChannel,
101
+ changes,
102
+ });
103
+ }
104
+ return true;
105
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * The root channel — `ahp-root://`.
3
+ *
4
+ * Exactly one root channel exists per host. It carries the agents this host can
5
+ * speak to plus host-level config. The session catalogue is deliberately *not*
6
+ * root state: clients fetch it with `listSessions` and patch it from
7
+ * `root/session*` notifications.
8
+ *
9
+ * @see https://microsoft.github.io/agent-host-protocol/specification/root-channel
10
+ */
11
+ import { ROOT_CHANNEL } from "../core/channels.js";
12
+ function initialRootState(agents = []) {
13
+ return { agents, activeSessions: 0 };
14
+ }
15
+ /** Registers `ahp-root://` on the host. Must run before any client connects. */
16
+ export function installRootChannel(host, agents = []) {
17
+ host.store.create(ROOT_CHANNEL, initialRootState(agents));
18
+ }
19
+ // ── Catalogue notifications ───────────────────────────────────────────────
20
+ // Ephemeral and never replayed on reconnect; after reconnecting a client
21
+ // re-fetches the catalogue with `listSessions`.
22
+ export function notifySessionAdded(host, summary) {
23
+ host.notify(ROOT_CHANNEL, "root/sessionAdded", { summary });
24
+ }
25
+ export function notifySessionRemoved(host, session) {
26
+ host.notify(ROOT_CHANNEL, "root/sessionRemoved", { session });
27
+ }
28
+ export function notifySessionSummaryChanged(host, session, changes) {
29
+ host.notify(ROOT_CHANNEL, "root/sessionSummaryChanged", { session, changes });
30
+ }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * The session channel — `ahp-session:/<uuid>`.
3
+ *
4
+ * A session is the coordination scope; the conversation itself lives on a chat
5
+ * channel underneath it. Creation is asynchronous by design: the host returns
6
+ * immediately with `lifecycle: 'creating'` and dispatches `session/ready` (or
7
+ * `session/creationFailed`) once the backend is up, so a slow agent start never
8
+ * blocks the client's round-trip.
9
+ *
10
+ *
11
+ * @see https://microsoft.github.io/agent-host-protocol/specification/session-channel
12
+ */
13
+ import { SessionLifecycle, SessionStatus, } from "@microsoft/agent-host-protocol";
14
+ import { pathToFileUri } from "../core/uri.js";
15
+ export function initialSessionState(provider, title, workingDirectory) {
16
+ return {
17
+ provider,
18
+ title,
19
+ status: SessionStatus.Idle,
20
+ lifecycle: SessionLifecycle.Creating,
21
+ workingDirectories: [pathToFileUri(workingDirectory)],
22
+ activeClients: [],
23
+ chats: [],
24
+ };
25
+ }
26
+ /** Bits 0–4 are mutually exclusive activity; later bits are session metadata. */
27
+ const STATUS_ACTIVITY_MASK = (1 << 5) - 1;
28
+ function timestamp(summary) {
29
+ const value = Date.parse(summary.modifiedAt);
30
+ return Number.isFinite(value) ? value : Number.NEGATIVE_INFINITY;
31
+ }
32
+ function mostRecent(chats, matches) {
33
+ let latest;
34
+ for (const chat of chats) {
35
+ if (matches(chat) && (!latest || timestamp(chat) > timestamp(latest))) {
36
+ latest = chat;
37
+ }
38
+ }
39
+ return latest;
40
+ }
41
+ /**
42
+ * Projects the session-level summary fields AHP derives from its chat catalog.
43
+ *
44
+ * The current host exposes one chat, so this is a direct pass-through today.
45
+ * Keeping the complete 0.9 rule here makes the projection deterministic and
46
+ * avoids teaching the pi adapter about protocol status bits.
47
+ */
48
+ export function aggregateSessionChats(state) {
49
+ if (state.chats.length === 0) {
50
+ return {
51
+ status: state.status,
52
+ ...(state.activity !== undefined ? { activity: state.activity } : {}),
53
+ };
54
+ }
55
+ const latest = mostRecent(state.chats, () => true);
56
+ if (!latest) {
57
+ return { status: state.status };
58
+ }
59
+ let driver = state.chats.find((chat) => chat.resource === state.defaultChat) ?? latest;
60
+ const inputNeeded = mostRecent(state.chats, (chat) => (chat.status & SessionStatus.InputNeeded) === SessionStatus.InputNeeded);
61
+ const error = mostRecent(state.chats, (chat) => (chat.status & SessionStatus.Error) === SessionStatus.Error);
62
+ if (inputNeeded) {
63
+ driver = inputNeeded;
64
+ }
65
+ else if (error) {
66
+ driver = error;
67
+ }
68
+ const metadataBits = state.status & ~STATUS_ACTIVITY_MASK;
69
+ const activityBits = driver.status & STATUS_ACTIVITY_MASK;
70
+ return {
71
+ status: (metadataBits | activityBits),
72
+ ...(driver.activity !== undefined ? { activity: driver.activity } : {}),
73
+ modifiedAt: latest.modifiedAt,
74
+ };
75
+ }
76
+ export function sessionSummaryOf(resource, createdAt, state, meta) {
77
+ const aggregate = aggregateSessionChats(state);
78
+ return {
79
+ resource,
80
+ provider: state.provider,
81
+ title: state.title,
82
+ status: aggregate.status,
83
+ // Root summary activity is deliberately omitted for AHP 0.9: its partial
84
+ // update shape cannot distinguish "clear" from "unchanged" on JSON wire.
85
+ createdAt,
86
+ modifiedAt: aggregate.modifiedAt ?? createdAt,
87
+ ...(state.workingDirectories ? { workingDirectories: state.workingDirectories } : {}),
88
+ ...(meta ? { _meta: meta } : {}),
89
+ };
90
+ }
@@ -0,0 +1,9 @@
1
+ /** Root catalogue projection; terminal process handles never enter protocol state. */
2
+ export function terminalInfo(resource, state) {
3
+ return {
4
+ resource,
5
+ title: state.title,
6
+ claim: state.claim,
7
+ lifecycle: state.lifecycle,
8
+ };
9
+ }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Channel URI scheme helpers.
3
+ *
4
+ * Channels are the routing key for the whole protocol: every command and every
5
+ * notification carries `params.channel`, so `(method, channel)` is enough to
6
+ * dispatch a message.
7
+ *
8
+ * @see https://microsoft.github.io/agent-host-protocol/specification/subscriptions
9
+ */
10
+ export const ROOT_CHANNEL = "ahp-root://";
11
+ const SESSION_SCHEME = "ahp-session:";
12
+ const CHAT_SCHEME = "ahp-chat:";
13
+ const TERMINAL_SCHEME = "ahp-terminal:";
14
+ const CHANGESET_SCHEME = "ahp-changeset:";
15
+ export const RESOURCE_WATCH_SCHEME = "ahp-resource-watch:";
16
+ /** Whether an action namespace belongs to the reducer behind a channel. */
17
+ export function actionBelongsToChannel(type, kind) {
18
+ return typeof type === "string" && type.startsWith(`${kind}/`);
19
+ }
20
+ function isRootChannel(uri) {
21
+ return uri === ROOT_CHANNEL;
22
+ }
23
+ function isSessionChannel(uri) {
24
+ return uri.startsWith(`${SESSION_SCHEME}/`);
25
+ }
26
+ export function isChatChannel(uri) {
27
+ return uri.startsWith(`${CHAT_SCHEME}/`);
28
+ }
29
+ /**
30
+ * Classifies a channel URI, or `undefined` for a scheme this host does not
31
+ * serve.
32
+ *
33
+ * Deliberately strict: it drives `subscribe`, where guessing wrong would create
34
+ * a channel with the wrong reducer. A command that creates a resource can
35
+ * register its client-chosen URI with an explicit kind instead.
36
+ */
37
+ export function channelKind(uri) {
38
+ if (isRootChannel(uri)) {
39
+ return "root";
40
+ }
41
+ if (isSessionChannel(uri)) {
42
+ return "session";
43
+ }
44
+ if (isChatChannel(uri)) {
45
+ return "chat";
46
+ }
47
+ if (uri.startsWith(`${TERMINAL_SCHEME}/`)) {
48
+ return "terminal";
49
+ }
50
+ if (uri.startsWith(`${CHANGESET_SCHEME}/`)) {
51
+ return "changeset";
52
+ }
53
+ if (uri.startsWith(`${RESOURCE_WATCH_SCHEME}/`)) {
54
+ return "resourceWatch";
55
+ }
56
+ return undefined;
57
+ }
58
+ function parseSingleSegmentChannel(uri) {
59
+ const match = /^([a-zA-Z][a-zA-Z0-9+.-]*):\/([^/?#]+)$/.exec(uri);
60
+ const scheme = match?.[1];
61
+ const id = match?.[2];
62
+ return scheme && id ? { scheme: scheme.toLowerCase(), id } : undefined;
63
+ }
64
+ /**
65
+ * Identifies a session from its canonical scheme or explicit provider aliases
66
+ * given as bare scheme names. Shape alone never makes an unknown URI a session.
67
+ */
68
+ export function sessionIdFromUri(uri, providerAliases = []) {
69
+ const parsed = parseSingleSegmentChannel(uri);
70
+ if (!parsed) {
71
+ return undefined;
72
+ }
73
+ const canonical = SESSION_SCHEME.slice(0, -1);
74
+ return parsed.scheme === canonical || providerAliases.some((alias) => parsed.scheme === alias.toLowerCase())
75
+ ? parsed.id
76
+ : undefined;
77
+ }
78
+ export function sessionUri(sessionId) {
79
+ return `${SESSION_SCHEME}/${sessionId}`;
80
+ }
81
+ /** `ahp-chat:/<id>` → `<id>`. Returns `undefined` when the URI is not a chat. */
82
+ export function chatIdFromUri(uri) {
83
+ return isChatChannel(uri) ? uri.slice(`${CHAT_SCHEME}/`.length) || undefined : undefined;
84
+ }
85
+ export function chatUri(chatId) {
86
+ return `${CHAT_SCHEME}/${chatId}`;
87
+ }