omp-channel 0.0.0-stage → 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.
@@ -0,0 +1,50 @@
1
+ import type { Limits } from "./protocol.js";
2
+ export declare const DEFAULT_CONFIG_RELATIVE_PATH: string;
3
+ export declare class ConfigError extends Error {
4
+ constructor(message: string);
5
+ }
6
+ /** Reads text, or returns undefined when the file does not exist. Other errors are thrown. */
7
+ export type ReadText = (path: string) => string | undefined;
8
+ export interface ServiceConfig {
9
+ readonly url: URL;
10
+ readonly key: string;
11
+ readonly requestTimeoutMs: number;
12
+ readonly paths: {
13
+ messages: string;
14
+ ack: string;
15
+ replies: string;
16
+ status: string;
17
+ };
18
+ }
19
+ export interface PollConfig {
20
+ readonly intervalMs: number;
21
+ readonly maxBackoffMs: number;
22
+ readonly batchSize: number;
23
+ }
24
+ export interface DeliveryConfig {
25
+ readonly deliverAs: "steer" | "followUp" | "aside";
26
+ }
27
+ export interface ChannelConfig {
28
+ readonly mcpServer: string;
29
+ readonly service: ServiceConfig | undefined;
30
+ readonly adapterModule: string | undefined;
31
+ readonly poll: PollConfig;
32
+ readonly limits: Limits & {
33
+ maxPending: number;
34
+ };
35
+ readonly delivery: DeliveryConfig;
36
+ }
37
+ export interface ConfigSources {
38
+ readonly env: Readonly<Record<string, string | undefined>>;
39
+ readonly cwd: string;
40
+ readonly readText: ReadText;
41
+ }
42
+ /**
43
+ * Loads the configuration. The file is OMP_CHANNEL_CONFIG when set, otherwise
44
+ * <cwd>/.omp/omp-channel.json when it exists, otherwise built-in defaults.
45
+ * The key is read from the environment variable named by service.keyEnv, or from the file named
46
+ * by <keyEnv>_FILE. It is never read from the configuration file.
47
+ */
48
+ export declare function loadConfig(sources: ConfigSources): ChannelConfig;
49
+ /** https is required. Plain http is accepted only for loopback, and credentials are refused. */
50
+ export declare function parseServiceUrl(raw: string): URL;
package/dist/config.js ADDED
@@ -0,0 +1,139 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { Ajv2020 } from "ajv/dist/2020.js";
4
+ export const DEFAULT_CONFIG_RELATIVE_PATH = join(".omp", "omp-channel.json");
5
+ export class ConfigError extends Error {
6
+ constructor(message) {
7
+ super(message);
8
+ this.name = "ConfigError";
9
+ }
10
+ }
11
+ const schemaUrl = new URL("../schema/config.schema.json", import.meta.url);
12
+ const ajv = new Ajv2020({ allErrors: false, strict: true, useDefaults: true, verbose: true });
13
+ const validateConfigFile = ajv.compile(JSON.parse(readFileSync(schemaUrl, "utf8")));
14
+ /**
15
+ * Loads the configuration. The file is OMP_CHANNEL_CONFIG when set, otherwise
16
+ * <cwd>/.omp/omp-channel.json when it exists, otherwise built-in defaults.
17
+ * The key is read from the environment variable named by service.keyEnv, or from the file named
18
+ * by <keyEnv>_FILE. It is never read from the configuration file.
19
+ */
20
+ export function loadConfig(sources) {
21
+ const path = nonEmpty(sources.env.OMP_CHANNEL_CONFIG) ?? join(sources.cwd, DEFAULT_CONFIG_RELATIVE_PATH);
22
+ const explicit = nonEmpty(sources.env.OMP_CHANNEL_CONFIG) !== undefined;
23
+ const text = sources.readText(path);
24
+ if (text === undefined && explicit) {
25
+ throw new ConfigError("OMP_CHANNEL_CONFIG points to a file that does not exist");
26
+ }
27
+ let raw = {};
28
+ if (text !== undefined) {
29
+ try {
30
+ raw = JSON.parse(text);
31
+ }
32
+ catch {
33
+ throw new ConfigError("the configuration file is not valid JSON");
34
+ }
35
+ }
36
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
37
+ throw new ConfigError("the configuration file must be a JSON object");
38
+ }
39
+ const data = { ...raw };
40
+ if (!validateConfigFile(data)) {
41
+ const first = validateConfigFile.errors?.[0];
42
+ throw new ConfigError(`invalid configuration: ${first === undefined ? "unknown error" : describeSchemaError(first)}`);
43
+ }
44
+ const parsed = data;
45
+ const service = parsed.service === undefined ? undefined : loadService(parsed.service, sources);
46
+ return {
47
+ mcpServer: parsed.mcpServer,
48
+ service,
49
+ adapterModule: parsed.adapterModule,
50
+ poll: parsed.poll,
51
+ limits: parsed.limits,
52
+ delivery: parsed.delivery,
53
+ };
54
+ }
55
+ /**
56
+ * Turns a schema error into one sentence that names the place and what is allowed. It never
57
+ * prints the rejected value, so a mistyped key cannot reach a log through this message.
58
+ */
59
+ function describeSchemaError(error) {
60
+ const params = error.params;
61
+ const place = error.instancePath === "" ? "the file" : error.instancePath;
62
+ const allowed = error.parentSchema
63
+ ?.properties;
64
+ switch (error.keyword) {
65
+ case "additionalProperties": {
66
+ const keys = Object.keys(allowed ?? {}).filter((key) => key !== "$schema");
67
+ const list = keys.length === 0 ? "" : ` (allowed: ${keys.join(", ")})`;
68
+ return `unknown key "${String(params.additionalProperty)}" at ${place}${list}`;
69
+ }
70
+ case "required":
71
+ return `missing required key "${String(params.missingProperty)}" at ${place}`;
72
+ case "enum":
73
+ return `${place} must be one of: ${params.allowedValues.join(", ")}`;
74
+ case "minimum":
75
+ return `${place} must be at least ${String(params.limit)}`;
76
+ case "maximum":
77
+ return `${place} must be at most ${String(params.limit)}`;
78
+ case "type":
79
+ return `${place} must be ${article(String(params.type))}`;
80
+ case "pattern":
81
+ return `${place} has an invalid format`;
82
+ case "minLength":
83
+ return `${place} is too short`;
84
+ case "maxLength":
85
+ return `${place} is too long`;
86
+ default:
87
+ return `${place} ${error.message ?? "is invalid"}`;
88
+ }
89
+ }
90
+ function article(type) {
91
+ return type === "integer" || type === "object" ? `an ${type}` : `a ${type}`;
92
+ }
93
+ function loadService(service, sources) {
94
+ const url = parseServiceUrl(service.url);
95
+ const key = readKey(service.keyEnv, sources);
96
+ return { url, key, requestTimeoutMs: service.requestTimeoutMs, paths: service.paths };
97
+ }
98
+ /** https is required. Plain http is accepted only for loopback, and credentials are refused. */
99
+ export function parseServiceUrl(raw) {
100
+ let url;
101
+ try {
102
+ url = new URL(raw);
103
+ }
104
+ catch {
105
+ throw new ConfigError("service.url is not a valid URL");
106
+ }
107
+ if (url.username !== "" || url.password !== "") {
108
+ throw new ConfigError("service.url must not contain credentials");
109
+ }
110
+ const loopback = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]";
111
+ if (url.protocol === "https:" || (url.protocol === "http:" && loopback)) {
112
+ return url;
113
+ }
114
+ throw new ConfigError("service.url must use https (http is allowed only for loopback)");
115
+ }
116
+ function readKey(keyEnv, sources) {
117
+ const direct = nonEmpty(sources.env[keyEnv]);
118
+ if (direct !== undefined) {
119
+ return direct;
120
+ }
121
+ const filePath = nonEmpty(sources.env[`${keyEnv}_FILE`]);
122
+ if (filePath !== undefined) {
123
+ const text = sources.readText(filePath);
124
+ const key = text === undefined ? undefined : nonEmpty(text);
125
+ if (key !== undefined) {
126
+ return key;
127
+ }
128
+ throw new ConfigError(`${keyEnv}_FILE cannot be read or is empty`);
129
+ }
130
+ throw new ConfigError(`set ${keyEnv} (or ${keyEnv}_FILE) to the service key`);
131
+ }
132
+ function nonEmpty(value) {
133
+ if (value === undefined) {
134
+ return undefined;
135
+ }
136
+ const trimmed = value.trim();
137
+ return trimmed.length === 0 ? undefined : trimmed;
138
+ }
139
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,OAAO,EAAoB,MAAM,kBAAkB,CAAC;AAG7D,MAAM,CAAC,MAAM,4BAA4B,GAAG,IAAI,CAAC,MAAM,EAAE,kBAAkB,CAAC,CAAC;AAE7E,MAAM,OAAO,WAAY,SAAQ,KAAK;IACpC,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,aAAa,CAAC;IAC5B,CAAC;CACF;AAqCD,MAAM,SAAS,GAAG,IAAI,GAAG,CAAC,8BAA8B,EAA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,CAAC,CAAC;IAC7C,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;QACzB,OAAO,MAAM,CAAC;IAChB,CAAC;IACD,MAAM,QAAQ,GAAG,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,MAAM,OAAO,CAAC,CAAC,CAAC;IACzD,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;QAC3B,MAAM,IAAI,GAAG,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;QACxC,MAAM,GAAG,GAAG,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;QAC5D,IAAI,GAAG,KAAK,SAAS,EAAE,CAAC;YACtB,OAAO,GAAG,CAAC;QACb,CAAC;QACD,MAAM,IAAI,WAAW,CAAC,GAAG,MAAM,kCAAkC,CAAC,CAAC;IACrE,CAAC;IACD,MAAM,IAAI,WAAW,CAAC,OAAO,MAAM,QAAQ,MAAM,2BAA2B,CAAC,CAAC;AAChF,CAAC;AAED,SAAS,QAAQ,CAAC,KAAyB;IACzC,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;QACxB,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,MAAM,OAAO,GAAG,KAAK,CAAC,IAAI,EAAE,CAAC;IAC7B,OAAO,OAAO,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC;AACpD,CAAC"}
@@ -0,0 +1,46 @@
1
+ import { type ChannelAdapter } from "./adapter.js";
2
+ import type { ChannelConfig } from "./config.js";
3
+ import type { SendUserMessageOptions } from "@oh-my-pi/pi-coding-agent/session/agent-session-types";
4
+ import { type AgentStatus, type InboundEvent } from "./protocol.js";
5
+ /** What happened to an inbound event. The outcomes marked as acknowledged may be acked. */
6
+ export type AdmitOutcome = "admitted" | "duplicate" | "ignored" | "refused" | "rejected" | "dropped";
7
+ export declare const ACKNOWLEDGED_OUTCOMES: ReadonlySet<AdmitOutcome>;
8
+ /** The part of the Oh My Pi session that the dispatcher uses. */
9
+ export interface SessionPort {
10
+ send(content: string, options: SendUserMessageOptions): Promise<void>;
11
+ abort(): void;
12
+ isIdle(): boolean;
13
+ }
14
+ export interface DispatcherOptions {
15
+ readonly config: ChannelConfig;
16
+ readonly session: SessionPort;
17
+ readonly adapter: ChannelAdapter | undefined;
18
+ readonly log: (line: string) => void;
19
+ readonly now?: () => Date;
20
+ readonly newId?: () => string;
21
+ }
22
+ export type ReplyResult = {
23
+ ok: true;
24
+ } | {
25
+ ok: false;
26
+ reason: string;
27
+ };
28
+ /**
29
+ * Applies inbound events to the agent session, one at a time and in arrival order.
30
+ *
31
+ * - One conversation is open at a time. Messages of another conversation are refused and are not
32
+ * acknowledged, so the service delivers them again once the open conversation closes.
33
+ * - A message is admitted once. Duplicates (same messageId, or same delivery) are acknowledged
34
+ * without running again.
35
+ * - Interrupt stops the current turn only. Tool results already produced stay in the session.
36
+ * - Agent state is reported to the service for the open conversation.
37
+ */
38
+ export declare class Dispatcher {
39
+ #private;
40
+ constructor(options: DispatcherOptions);
41
+ get activeConversation(): string | undefined;
42
+ submit(event: InboundEvent, deliveryId?: string): Promise<AdmitOutcome>;
43
+ /** Reports the agent state for the open conversation. Best effort: errors are logged. */
44
+ setStatus(status: AgentStatus): void;
45
+ reply(messageId: string, text: string): Promise<ReplyResult>;
46
+ }
@@ -0,0 +1,191 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { AdapterError } from "./adapter.js";
3
+ import { buildReply, buildStatus, formatForSession, } from "./protocol.js";
4
+ export const ACKNOWLEDGED_OUTCOMES = new Set([
5
+ "admitted",
6
+ "duplicate",
7
+ "ignored",
8
+ ]);
9
+ const MAX_REMEMBERED = 1000;
10
+ /**
11
+ * Applies inbound events to the agent session, one at a time and in arrival order.
12
+ *
13
+ * - One conversation is open at a time. Messages of another conversation are refused and are not
14
+ * acknowledged, so the service delivers them again once the open conversation closes.
15
+ * - A message is admitted once. Duplicates (same messageId, or same delivery) are acknowledged
16
+ * without running again.
17
+ * - Interrupt stops the current turn only. Tool results already produced stay in the session.
18
+ * - Agent state is reported to the service for the open conversation.
19
+ */
20
+ export class Dispatcher {
21
+ #options;
22
+ #queue = Promise.resolve();
23
+ #pending = 0;
24
+ #active;
25
+ #remembered = new RecentSet(MAX_REMEMBERED);
26
+ #conversationOf = new RecentMap(MAX_REMEMBERED);
27
+ constructor(options) {
28
+ this.#options = options;
29
+ }
30
+ get activeConversation() {
31
+ return this.#active;
32
+ }
33
+ submit(event, deliveryId) {
34
+ if (this.#pending >= this.#options.config.limits.maxPending) {
35
+ return Promise.resolve("dropped");
36
+ }
37
+ this.#pending += 1;
38
+ const run = this.#queue.then(async () => {
39
+ try {
40
+ return await this.#apply(event, deliveryId);
41
+ }
42
+ finally {
43
+ this.#pending -= 1;
44
+ }
45
+ });
46
+ this.#queue = run.catch(() => undefined);
47
+ return run;
48
+ }
49
+ /** Reports the agent state for the open conversation. Best effort: errors are logged. */
50
+ setStatus(status) {
51
+ const conversation = this.#active;
52
+ const adapter = this.#options.adapter;
53
+ if (conversation === undefined || adapter?.status === undefined) {
54
+ return;
55
+ }
56
+ adapter.status(buildStatus(conversation, status, this.#now())).catch((error) => {
57
+ this.#options.log(`status was not reported (${errorName(error)})`);
58
+ });
59
+ }
60
+ async reply(messageId, text) {
61
+ const conversation = this.#conversationOf.get(messageId);
62
+ if (conversation === undefined) {
63
+ return { ok: false, reason: "unknown messageId" };
64
+ }
65
+ const adapter = this.#options.adapter;
66
+ if (adapter === undefined) {
67
+ return { ok: false, reason: "replies are not configured" };
68
+ }
69
+ const reply = buildReply(conversation, messageId, text, {
70
+ messageId: this.#newId(),
71
+ at: this.#now(),
72
+ });
73
+ try {
74
+ await adapter.reply(reply);
75
+ return { ok: true };
76
+ }
77
+ catch (error) {
78
+ const detail = error instanceof AdapterError ? error.message : `the request failed (${errorName(error)})`;
79
+ return { ok: false, reason: `the service did not accept the reply: ${detail}` };
80
+ }
81
+ }
82
+ async #apply(event, deliveryId) {
83
+ const { config, session } = this.#options;
84
+ if (event.type === "message") {
85
+ return this.#applyMessage(event, config);
86
+ }
87
+ const key = deliveryId === undefined ? undefined : `delivery:${deliveryId}`;
88
+ if (key !== undefined && this.#remembered.has(key)) {
89
+ return "duplicate";
90
+ }
91
+ if (event.conversationId !== this.#active) {
92
+ return "ignored";
93
+ }
94
+ if (event.type === "interrupt") {
95
+ if (!session.isIdle()) {
96
+ session.abort();
97
+ }
98
+ if (key !== undefined) {
99
+ this.#remembered.add(key);
100
+ }
101
+ await this.#notify(() => this.#options.adapter?.interrupt?.(event.conversationId), "interrupt");
102
+ return "admitted";
103
+ }
104
+ this.#active = undefined;
105
+ if (key !== undefined) {
106
+ this.#remembered.add(key);
107
+ }
108
+ await this.#notify(() => this.#options.adapter?.close?.(event.conversationId), "close");
109
+ return "admitted";
110
+ }
111
+ async #applyMessage(event, config) {
112
+ const key = `message:${event.messageId}`;
113
+ if (this.#remembered.has(key)) {
114
+ return "duplicate";
115
+ }
116
+ if (this.#active !== undefined && this.#active !== event.conversationId) {
117
+ return "refused";
118
+ }
119
+ const options = {
120
+ deliverAs: config.delivery.deliverAs,
121
+ attribution: event.attribution,
122
+ };
123
+ try {
124
+ await this.#options.session.send(formatForSession(event), options);
125
+ }
126
+ catch (error) {
127
+ this.#options.log(`message ${event.messageId} was not admitted (${errorName(error)})`);
128
+ return "rejected";
129
+ }
130
+ this.#active = event.conversationId;
131
+ this.#remembered.add(key);
132
+ this.#conversationOf.set(event.messageId, event.conversationId);
133
+ return "admitted";
134
+ }
135
+ async #notify(call, label) {
136
+ try {
137
+ await call();
138
+ }
139
+ catch (error) {
140
+ this.#options.log(`${label} was not reported (${errorName(error)})`);
141
+ }
142
+ }
143
+ #now() {
144
+ return this.#options.now?.() ?? new Date();
145
+ }
146
+ #newId() {
147
+ return this.#options.newId?.() ?? randomUUID();
148
+ }
149
+ }
150
+ function errorName(error) {
151
+ return error instanceof Error ? error.name : "unknown";
152
+ }
153
+ class RecentSet {
154
+ #values = new Set();
155
+ #capacity;
156
+ constructor(capacity) {
157
+ this.#capacity = capacity;
158
+ }
159
+ has(value) {
160
+ return this.#values.has(value);
161
+ }
162
+ add(value) {
163
+ this.#values.add(value);
164
+ if (this.#values.size > this.#capacity) {
165
+ const oldest = this.#values.values().next();
166
+ if (oldest.value !== undefined) {
167
+ this.#values.delete(oldest.value);
168
+ }
169
+ }
170
+ }
171
+ }
172
+ class RecentMap {
173
+ #values = new Map();
174
+ #capacity;
175
+ constructor(capacity) {
176
+ this.#capacity = capacity;
177
+ }
178
+ get(key) {
179
+ return this.#values.get(key);
180
+ }
181
+ set(key, value) {
182
+ this.#values.set(key, value);
183
+ if (this.#values.size > this.#capacity) {
184
+ const oldest = this.#values.keys().next();
185
+ if (oldest.value !== undefined) {
186
+ this.#values.delete(oldest.value);
187
+ }
188
+ }
189
+ }
190
+ }
191
+ //# sourceMappingURL=dispatcher.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dispatcher.js","sourceRoot":"","sources":["../src/dispatcher.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,YAAY,EAAuB,MAAM,cAAc,CAAC;AAGjE,OAAO,EAEL,UAAU,EACV,WAAW,EACX,gBAAgB,GAGjB,MAAM,eAAe,CAAC;AAWvB,MAAM,CAAC,MAAM,qBAAqB,GAA8B,IAAI,GAAG,CAAC;IACtE,UAAU;IACV,WAAW;IACX,SAAS;CACV,CAAC,CAAC;AAoBH,MAAM,cAAc,GAAG,IAAI,CAAC;AAE5B;;;;;;;;;GASG;AACH,MAAM,OAAO,UAAU;IACZ,QAAQ,CAAoB;IACrC,MAAM,GAAqB,OAAO,CAAC,OAAO,EAAE,CAAC;IAC7C,QAAQ,GAAG,CAAC,CAAC;IACb,OAAO,CAAqB;IACnB,WAAW,GAAG,IAAI,SAAS,CAAC,cAAc,CAAC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F;AAED,MAAM,SAAS;IACJ,OAAO,GAAG,IAAI,GAAG,EAAkB,CAAC;IACpC,SAAS,CAAS;IAE3B,YAAY,QAAgB;QAC1B,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;IAC5B,CAAC;IAED,GAAG,CAAC,GAAW;QACb,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IAC/B,CAAC;IAED,GAAG,CAAC,GAAW,EAAE,KAAa;QAC5B,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QAC7B,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC,SAAS,EAAE,CAAC;YACvC,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,CAAC;YAC1C,IAAI,MAAM,CAAC,KAAK,KAAK,SAAS,EAAE,CAAC;gBAC/B,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YACpC,CAAC;QACH,CAAC;IACH,CAAC;CACF"}
@@ -0,0 +1,26 @@
1
+ import type { ExtensionFactory } from "@oh-my-pi/pi-coding-agent/extensibility/extensions/types";
2
+ import type { ChannelAdapter } from "./adapter.js";
3
+ import type { ChannelConfig } from "./config.js";
4
+ export declare const REPLY_TOOL_NAME = "reply";
5
+ export interface ChannelExtensionOptions {
6
+ readonly config: ChannelConfig;
7
+ /** Transport adapter (HTTP service or a custom module). Undefined: MCP push only, no replies. */
8
+ readonly adapter?: ChannelAdapter | undefined;
9
+ /** Receives short diagnostic lines. They never contain message text or keys. */
10
+ readonly log?: (line: string) => void;
11
+ }
12
+ /**
13
+ * Creates the extension factory. It registers:
14
+ * - `mcp_notification`: messages pushed by the configured MCP server enter the agent;
15
+ * - the `reply` tool: the model answers a message by its messageId;
16
+ * - lifecycle hooks: agent state is reported to the service, and the adapter stops on shutdown;
17
+ * - the adapter receive loop, when an adapter is given.
18
+ */
19
+ export declare function createChannelExtension(options: ChannelExtensionOptions): ExtensionFactory;
20
+ /** Name of the command that shows the channel state (`/channel-status`). */
21
+ export declare const STATUS_COMMAND_NAME = "channel-status";
22
+ /**
23
+ * The text of `/channel-status`: the transport in use, then the adapter's own description when it
24
+ * has one. A failing description is reported in one line and never shown raw.
25
+ */
26
+ export declare function channelStatusText(config: ChannelConfig, adapter: ChannelAdapter | undefined, log: (line: string) => void): Promise<string>;
@@ -0,0 +1,141 @@
1
+ import { ACKNOWLEDGED_OUTCOMES, Dispatcher } from "./dispatcher.js";
2
+ import { parseMcpNotification, parseReplyInput } from "./protocol.js";
3
+ import { jsonSchemaParameters } from "./tool-schema.js";
4
+ export const REPLY_TOOL_NAME = "reply";
5
+ /**
6
+ * Creates the extension factory. It registers:
7
+ * - `mcp_notification`: messages pushed by the configured MCP server enter the agent;
8
+ * - the `reply` tool: the model answers a message by its messageId;
9
+ * - lifecycle hooks: agent state is reported to the service, and the adapter stops on shutdown;
10
+ * - the adapter receive loop, when an adapter is given.
11
+ */
12
+ export function createChannelExtension(options) {
13
+ return (pi) => {
14
+ const { config } = options;
15
+ const adapter = options.adapter;
16
+ const log = options.log ?? (() => undefined);
17
+ let context;
18
+ const session = {
19
+ send: (content, sendOptions) => pi.sendUserMessage(content, sendOptions),
20
+ abort: () => context?.abort(),
21
+ isIdle: () => context?.isIdle() ?? true,
22
+ };
23
+ const dispatcher = new Dispatcher({ config, session, adapter, log });
24
+ pi.on("session_start", (_event, ctx) => {
25
+ context = ctx;
26
+ });
27
+ pi.on("mcp_notification", (event, ctx) => {
28
+ context = ctx;
29
+ const parsed = parseMcpNotification(event, config.mcpServer, config.limits);
30
+ if (parsed === null) {
31
+ return;
32
+ }
33
+ if (!parsed.ok) {
34
+ log(`dropped invalid MCP channel notification: ${parsed.reason}`);
35
+ return;
36
+ }
37
+ void dispatcher.submit(parsed.value).then((outcome) => {
38
+ if (!ACKNOWLEDGED_OUTCOMES.has(outcome)) {
39
+ log(`MCP channel event not admitted: ${outcome}`);
40
+ }
41
+ });
42
+ });
43
+ pi.on("agent_start", (_event, ctx) => {
44
+ context = ctx;
45
+ dispatcher.setStatus("working");
46
+ });
47
+ pi.on("agent_end", (_event, ctx) => {
48
+ context = ctx;
49
+ dispatcher.setStatus("free");
50
+ });
51
+ if (adapter !== undefined) {
52
+ const controller = new AbortController();
53
+ pi.on("session_shutdown", () => {
54
+ controller.abort();
55
+ });
56
+ void runReceiveLoop(adapter, dispatcher, controller.signal, log);
57
+ }
58
+ pi.registerTool({
59
+ name: REPLY_TOOL_NAME,
60
+ label: "Reply to service",
61
+ description: "Send a reply to an external message. Pass the messageId shown with that message. Only messageIds received in this session are accepted.",
62
+ parameters: jsonSchemaParameters({
63
+ type: "object",
64
+ properties: {
65
+ messageId: { type: "string", minLength: 1, maxLength: 128 },
66
+ text: { type: "string", minLength: 1, maxLength: config.limits.maxTextLength },
67
+ },
68
+ required: ["messageId", "text"],
69
+ additionalProperties: false,
70
+ }),
71
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
72
+ context = ctx;
73
+ const parsed = parseReplyInput(params, config.limits);
74
+ if (!parsed.ok) {
75
+ return textResult(`Reply rejected: ${parsed.reason}.`);
76
+ }
77
+ const result = await dispatcher.reply(parsed.value.messageId, parsed.value.text);
78
+ return textResult(result.ok ? "Reply sent." : `Reply not sent: ${result.reason}.`);
79
+ },
80
+ });
81
+ pi.registerCommand(STATUS_COMMAND_NAME, {
82
+ description: "Show how the channel is connected and what its adapter reports",
83
+ handler: async (_args, ctx) => {
84
+ ctx.ui.notify(await channelStatusText(config, adapter, log), "info");
85
+ },
86
+ });
87
+ };
88
+ }
89
+ /** Name of the command that shows the channel state (`/channel-status`). */
90
+ export const STATUS_COMMAND_NAME = "channel-status";
91
+ /**
92
+ * The text of `/channel-status`: the transport in use, then the adapter's own description when it
93
+ * has one. A failing description is reported in one line and never shown raw.
94
+ */
95
+ export async function channelStatusText(config, adapter, log) {
96
+ const transport = config.service !== undefined
97
+ ? "HTTP service"
98
+ : adapter !== undefined
99
+ ? "adapter module"
100
+ : "MCP push only (replies are not configured)";
101
+ const lines = [`Channel: ${transport}, MCP server ${config.mcpServer}.`];
102
+ if (adapter?.describe !== undefined) {
103
+ try {
104
+ lines.push(await adapter.describe());
105
+ }
106
+ catch {
107
+ log("the adapter could not describe its state");
108
+ lines.push("The adapter could not report its state.");
109
+ }
110
+ }
111
+ return lines.join("\n");
112
+ }
113
+ /**
114
+ * Takes deliveries from the adapter one at a time. A delivery is acknowledged only after the agent
115
+ * admitted it, so a crash before that point leads to redelivery rather than loss.
116
+ */
117
+ async function runReceiveLoop(adapter, dispatcher, signal, log) {
118
+ try {
119
+ for await (const delivery of adapter.receive(signal)) {
120
+ const outcome = await dispatcher.submit(delivery.event, delivery.deliveryId);
121
+ if (!ACKNOWLEDGED_OUTCOMES.has(outcome)) {
122
+ log(`delivery not admitted (${outcome}); the service will deliver it again`);
123
+ continue;
124
+ }
125
+ if (delivery.deliveryId !== undefined && adapter.ack !== undefined) {
126
+ await adapter.ack(delivery.deliveryId).catch(() => {
127
+ log("could not acknowledge a delivery; the service may deliver it again");
128
+ });
129
+ }
130
+ }
131
+ }
132
+ catch (error) {
133
+ if (!signal.aborted) {
134
+ log(`receive loop stopped (${error instanceof Error ? error.name : "unknown"})`);
135
+ }
136
+ }
137
+ }
138
+ function textResult(text) {
139
+ return { content: [{ type: "text", text }] };
140
+ }
141
+ //# sourceMappingURL=extension.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"extension.js","sourceRoot":"","sources":["../src/extension.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,qBAAqB,EAAE,UAAU,EAAoB,MAAM,iBAAiB,CAAC;AACtF,OAAO,EAAE,oBAAoB,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AACtE,OAAO,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AAExD,MAAM,CAAC,MAAM,eAAe,GAAG,OAAO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,CAAC,GAAG,KAAK,SAAS,EAAE,CAAC;gBACnE,MAAM,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE;oBAChD,GAAG,CAAC,oEAAoE,CAAC,CAAC;gBAC5E,CAAC,CAAC,CAAC;YACL,CAAC;QACH,CAAC;IACH,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;YACpB,GAAG,CAAC,yBAAyB,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,GAAG,CAAC,CAAC;QACnF,CAAC;IACH,CAAC;AACH,CAAC;AAED,SAAS,UAAU,CAAC,IAAY;IAC9B,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,EAAE,CAAC;AAC/C,CAAC"}
@@ -0,0 +1,19 @@
1
+ import { type ChannelAdapter } from "./adapter.js";
2
+ import type { PollConfig, ServiceConfig } from "./config.js";
3
+ import { type Limits } from "./protocol.js";
4
+ export interface HttpAdapterOptions {
5
+ readonly service: ServiceConfig;
6
+ readonly poll: PollConfig;
7
+ readonly limits: Limits;
8
+ readonly log: (line: string) => void;
9
+ /** Injected for tests. Defaults to the global fetch. */
10
+ readonly fetch?: typeof fetch;
11
+ }
12
+ /**
13
+ * Transport over plain HTTP with leases (see docs/protocol.md, "HTTP transport"):
14
+ * - GET paths.messages returns { deliveries: [{ deliveryId, leaseExpiresAt, event }] } in order;
15
+ * - POST paths.ack with { deliveryIds: [...] } after the agent admitted a delivery;
16
+ * - POST paths.replies with a reply; POST paths.status with an agent status.
17
+ * A delivery that is not acknowledged before its lease ends is delivered again by the service.
18
+ */
19
+ export declare function createHttpAdapter(options: HttpAdapterOptions): ChannelAdapter;