@theokit/gateway-agent 0.0.0-stage → 0.3.2

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,246 @@
1
+ import { MessageEvent, BasePlatformAdapter, GatewayHandler, GatewayHook, PlatformName } from '@theokit/gateway';
2
+ import { AgentOutputEvent } from '@theokit/presenter';
3
+
4
+ /**
5
+ * The part of an SDK Agent this package uses, so tests can pass a fake.
6
+ *
7
+ * @public
8
+ */
9
+ interface TurnAgent {
10
+ send(prompt: string, options?: Record<string, unknown>): Promise<{
11
+ stream(): AsyncIterable<{
12
+ readonly type: string;
13
+ }>;
14
+ wait(): Promise<{
15
+ status: string;
16
+ error?: {
17
+ code?: string;
18
+ };
19
+ }>;
20
+ }>;
21
+ }
22
+ /**
23
+ * What one turn produced: the text, and on failure a short code (never a message).
24
+ *
25
+ * @public
26
+ */
27
+ type AgentTextResult = {
28
+ readonly ok: true;
29
+ readonly text: string;
30
+ } | {
31
+ readonly ok: false;
32
+ readonly text: string;
33
+ readonly failure: string;
34
+ };
35
+ /**
36
+ * Runs one turn with tool results framed as untrusted data (`toolResultGuard.delimit`, merged
37
+ * over the caller's `sendOptions`). The turn failed when `wait()` reports `status: "error"` or the
38
+ * stream carried an error, even if `wait()` says it finished.
39
+ *
40
+ * @public
41
+ */
42
+ declare function runAgentText(agent: TurnAgent, prompt: string, options?: {
43
+ sendOptions?: Record<string, unknown>;
44
+ }): Promise<AgentTextResult>;
45
+
46
+ /**
47
+ * An agent for one event, and how to give it back.
48
+ *
49
+ * @public
50
+ */
51
+ interface AgentLease {
52
+ readonly agent: TurnAgent;
53
+ release(): void | Promise<void>;
54
+ }
55
+ /**
56
+ * How `createAgentHandler` finds its agent and what it sends besides the answer.
57
+ *
58
+ * @public
59
+ */
60
+ interface AgentHandlerOptions {
61
+ /** The agent for this event's session (e.g. from SessionRouter + the SDK registry). */
62
+ agentFor(event: MessageEvent): Promise<AgentLease>;
63
+ /** Prompt from the event. Default: event.text. */
64
+ prompt?(event: MessageEvent): string;
65
+ /** React to the inbound message when the turn starts. Typing is the runner's job. */
66
+ ackEmoji?: string;
67
+ /**
68
+ * The runner's adapters. Used to send the ack reaction on `@theokit/gateway` 0.20.x, whose
69
+ * context has no `react`. With neither, the reaction is skipped (logged once) and the turn
70
+ * still replies.
71
+ */
72
+ adapters?: ReadonlyArray<BasePlatformAdapter>;
73
+ /** Called with each progress line; return a line to send, or undefined to skip. Default: none sent. */
74
+ progress?(output: AgentOutputEvent): string | undefined;
75
+ /** Exact values masked out of every reply and progress line. */
76
+ secrets?: ReadonlyArray<string>;
77
+ noAnswerText?: string;
78
+ errorText?: string;
79
+ sendOptions?: Record<string, unknown>;
80
+ }
81
+ /**
82
+ * Turns an SDK agent into a `GatewayHandler`: one agent turn per message, exactly one reply
83
+ * (the answer, `noAnswerText` when empty, or `errorText` when the turn failed), after which a
84
+ * failed turn throws `AgentTurnError` so the runner fires `on_error`. The lease is always
85
+ * released. The handler starts no typing indicator; `GatewayRunner` does.
86
+ *
87
+ * @public
88
+ */
89
+ declare function createAgentHandler(options: AgentHandlerOptions): GatewayHandler;
90
+
91
+ /** What an owner answered: allow once, allow from now on, or refuse. */
92
+ type ApprovalAnswer = "once" | "always" | "deny";
93
+ /** Options for {@link createChatApprover}. */
94
+ interface ChatApproverOptions {
95
+ /** The conversation key of an event; must match what the app passes to `ask()`. */
96
+ conversationOf(event: MessageEvent): string;
97
+ isOwner(event: MessageEvent): boolean;
98
+ /** Posts text into the conversation of the last event seen with that key. */
99
+ send(event: MessageEvent, text: string): Promise<void>;
100
+ /** Default 120_000. */
101
+ readonly timeoutMs?: number;
102
+ /** Default: "Run this?\n<question>\nReply /approve, /approve always or /deny within <n> s." */
103
+ format?(question: string, timeoutMs: number): string;
104
+ }
105
+ /** An approver: a hook that reads the owner's answers and `ask` to put a question to them. */
106
+ interface ChatApprover {
107
+ /** Register in the runner's hooks; it blocks `/approve`, `/approve always` and `/deny`. */
108
+ readonly hook: GatewayHook;
109
+ /** Asks in the conversation and waits. Resolves `deny` on silence, send failure or no open conversation. */
110
+ ask(conversation: string, question: string): Promise<{
111
+ readonly answer: ApprovalAnswer;
112
+ readonly by?: string;
113
+ }>;
114
+ hasPending(event: MessageEvent): boolean;
115
+ }
116
+ /** Asks an owner in the chat to `/approve`, `/approve always` or `/deny`, and waits for the answer. */
117
+ declare function createChatApprover(options: ChatApproverOptions): ChatApprover;
118
+
119
+ /**
120
+ * Structurally equal to `@theokit/agents`' `DeliverPort`; no dependency on `@theokit/agents`.
121
+ *
122
+ * @public
123
+ */
124
+ type GatewayDeliverPort = (target: {
125
+ readonly platform: string;
126
+ readonly channelId: string;
127
+ }, text: string) => Promise<{
128
+ ok: boolean;
129
+ error?: {
130
+ code: string;
131
+ };
132
+ }>;
133
+ /**
134
+ * Adapts gateway adapters to a scheduler's deliver port. `adapters` is read on every send, so a
135
+ * platform that connected later is reached. Text is masked with `options.secrets`, rendered for the
136
+ * platform and sent with `deliverText`. Failures are codes: `not_started` (no adapter for the
137
+ * platform), the adapter's refusal code, or `adapter_threw`.
138
+ *
139
+ * @public
140
+ */
141
+ declare function gatewayDeliverPort(adapters: () => Iterable<BasePlatformAdapter>, options?: {
142
+ secrets?: ReadonlyArray<string>;
143
+ }): GatewayDeliverPort;
144
+ /**
145
+ * Parses `"<platform>:<channelId>"`, split at the first colon, so a channel id may contain more
146
+ * colons (Matrix room ids). Throws `GatewayConfigurationError` with code `invalid_channel_target`
147
+ * when a part is missing; the message never quotes the channel id.
148
+ *
149
+ * @public
150
+ */
151
+ declare function parseChannelTarget(spec: string): {
152
+ platform: PlatformName;
153
+ channelId: string;
154
+ };
155
+
156
+ /**
157
+ * Renders `text` for the adapter's platform and sends it. Resolves `undefined` on success, or a
158
+ * short failure code: the adapter's refusal code, or the thrown error's name. Never a message
159
+ * or an id.
160
+ *
161
+ * @public
162
+ */
163
+ declare function deliverText(adapter: BasePlatformAdapter, channelId: string, text: string, channelType?: "dm" | "group"): Promise<string | undefined>;
164
+
165
+ /**
166
+ * A turn that failed. Carries the platform and the SDK error code only: never the prompt, the
167
+ * answer or an error message from the model.
168
+ *
169
+ * @public
170
+ */
171
+ declare class AgentTurnError extends Error {
172
+ readonly platform: string;
173
+ readonly code: string;
174
+ constructor(platform: string, code: string);
175
+ }
176
+
177
+ /**
178
+ * Wraps untrusted text in a named tag, escaping a forged closing tag (`</tag`, any case) so the
179
+ * body cannot end the frame early. Attribute values are escaped too. Throws `TypeError` when `tag`
180
+ * or an attribute name is not a plain name.
181
+ *
182
+ * @public
183
+ */
184
+ declare function frameUntrusted(tag: string, body: string, attributes?: Record<string, string>): string;
185
+
186
+ /**
187
+ * Same shape as theokit/server/webhook `VerifyFn`, declared here structurally.
188
+ *
189
+ * @public
190
+ */
191
+ type TriggerVerify = (request: Request) => Promise<{
192
+ readonly ok: boolean;
193
+ }>;
194
+ /**
195
+ * What `createTrigger` needs: how to verify, where the answer goes, and which agent runs.
196
+ *
197
+ * @public
198
+ */
199
+ interface TriggerOptions {
200
+ readonly name: string;
201
+ readonly verify: TriggerVerify;
202
+ /** The adapter and channel the answer goes to; undefined adapter means "not started". */
203
+ deliverTo(): {
204
+ readonly adapter: BasePlatformAdapter | undefined;
205
+ readonly channelId: string;
206
+ };
207
+ /** A fresh agent per run; released after the run. */
208
+ agent(): Promise<AgentLease>;
209
+ /** Instructions placed before the framed body. */
210
+ readonly instructions?: string;
211
+ /** Header carrying the delivery id. Default "x-delivery-id"; GitHub users pass "x-github-delivery". */
212
+ readonly dedupeHeader?: string;
213
+ /** How many delivery ids are remembered, oldest dropped first. Default 1000. */
214
+ readonly rememberDeliveries?: number;
215
+ /**
216
+ * Failure codes, besides a built-in list, that may be written as they are. Any other code from
217
+ * the agent or the adapter is written as `unknown`, because a code can echo request data.
218
+ */
219
+ readonly failureCodes?: ReadonlyArray<string>;
220
+ /** Exact values masked out of the reply. */
221
+ readonly secrets?: ReadonlyArray<string>;
222
+ /** Receives one line per failure: a code only, never the body or headers. Default: none. */
223
+ readonly write?: (line: string) => void;
224
+ }
225
+ /**
226
+ * A webhook handler that runs an agent on each new signed delivery.
227
+ *
228
+ * @public
229
+ */
230
+ interface Trigger {
231
+ handle(request: Request): Promise<Response>;
232
+ /** Resolves when every run started so far has ended (for shutdown and tests). */
233
+ idle(): Promise<void>;
234
+ }
235
+ /**
236
+ * Builds a trigger: verifies the request (401 on failure, nothing read), refuses a delivery id
237
+ * over 256 chars (400), answers 503 while the reply adapter is not started (the id is not
238
+ * remembered, so the retry runs), 200 for an id seen before, and otherwise 202 while one run
239
+ * starts in the background. The answer is masked and sent to the channel; a failed run or
240
+ * undelivered reply is written as one line holding a code.
241
+ *
242
+ * @public
243
+ */
244
+ declare function createTrigger(options: TriggerOptions): Trigger;
245
+
246
+ export { type AgentHandlerOptions, type AgentLease, type AgentTextResult, AgentTurnError, type ApprovalAnswer, type ChatApprover, type ChatApproverOptions, type GatewayDeliverPort, type Trigger, type TriggerOptions, type TriggerVerify, type TurnAgent, createAgentHandler, createChatApprover, createTrigger, deliverText, frameUntrusted, gatewayDeliverPort, parseChannelTarget, runAgentText };
@@ -0,0 +1,246 @@
1
+ import { MessageEvent, BasePlatformAdapter, GatewayHandler, GatewayHook, PlatformName } from '@theokit/gateway';
2
+ import { AgentOutputEvent } from '@theokit/presenter';
3
+
4
+ /**
5
+ * The part of an SDK Agent this package uses, so tests can pass a fake.
6
+ *
7
+ * @public
8
+ */
9
+ interface TurnAgent {
10
+ send(prompt: string, options?: Record<string, unknown>): Promise<{
11
+ stream(): AsyncIterable<{
12
+ readonly type: string;
13
+ }>;
14
+ wait(): Promise<{
15
+ status: string;
16
+ error?: {
17
+ code?: string;
18
+ };
19
+ }>;
20
+ }>;
21
+ }
22
+ /**
23
+ * What one turn produced: the text, and on failure a short code (never a message).
24
+ *
25
+ * @public
26
+ */
27
+ type AgentTextResult = {
28
+ readonly ok: true;
29
+ readonly text: string;
30
+ } | {
31
+ readonly ok: false;
32
+ readonly text: string;
33
+ readonly failure: string;
34
+ };
35
+ /**
36
+ * Runs one turn with tool results framed as untrusted data (`toolResultGuard.delimit`, merged
37
+ * over the caller's `sendOptions`). The turn failed when `wait()` reports `status: "error"` or the
38
+ * stream carried an error, even if `wait()` says it finished.
39
+ *
40
+ * @public
41
+ */
42
+ declare function runAgentText(agent: TurnAgent, prompt: string, options?: {
43
+ sendOptions?: Record<string, unknown>;
44
+ }): Promise<AgentTextResult>;
45
+
46
+ /**
47
+ * An agent for one event, and how to give it back.
48
+ *
49
+ * @public
50
+ */
51
+ interface AgentLease {
52
+ readonly agent: TurnAgent;
53
+ release(): void | Promise<void>;
54
+ }
55
+ /**
56
+ * How `createAgentHandler` finds its agent and what it sends besides the answer.
57
+ *
58
+ * @public
59
+ */
60
+ interface AgentHandlerOptions {
61
+ /** The agent for this event's session (e.g. from SessionRouter + the SDK registry). */
62
+ agentFor(event: MessageEvent): Promise<AgentLease>;
63
+ /** Prompt from the event. Default: event.text. */
64
+ prompt?(event: MessageEvent): string;
65
+ /** React to the inbound message when the turn starts. Typing is the runner's job. */
66
+ ackEmoji?: string;
67
+ /**
68
+ * The runner's adapters. Used to send the ack reaction on `@theokit/gateway` 0.20.x, whose
69
+ * context has no `react`. With neither, the reaction is skipped (logged once) and the turn
70
+ * still replies.
71
+ */
72
+ adapters?: ReadonlyArray<BasePlatformAdapter>;
73
+ /** Called with each progress line; return a line to send, or undefined to skip. Default: none sent. */
74
+ progress?(output: AgentOutputEvent): string | undefined;
75
+ /** Exact values masked out of every reply and progress line. */
76
+ secrets?: ReadonlyArray<string>;
77
+ noAnswerText?: string;
78
+ errorText?: string;
79
+ sendOptions?: Record<string, unknown>;
80
+ }
81
+ /**
82
+ * Turns an SDK agent into a `GatewayHandler`: one agent turn per message, exactly one reply
83
+ * (the answer, `noAnswerText` when empty, or `errorText` when the turn failed), after which a
84
+ * failed turn throws `AgentTurnError` so the runner fires `on_error`. The lease is always
85
+ * released. The handler starts no typing indicator; `GatewayRunner` does.
86
+ *
87
+ * @public
88
+ */
89
+ declare function createAgentHandler(options: AgentHandlerOptions): GatewayHandler;
90
+
91
+ /** What an owner answered: allow once, allow from now on, or refuse. */
92
+ type ApprovalAnswer = "once" | "always" | "deny";
93
+ /** Options for {@link createChatApprover}. */
94
+ interface ChatApproverOptions {
95
+ /** The conversation key of an event; must match what the app passes to `ask()`. */
96
+ conversationOf(event: MessageEvent): string;
97
+ isOwner(event: MessageEvent): boolean;
98
+ /** Posts text into the conversation of the last event seen with that key. */
99
+ send(event: MessageEvent, text: string): Promise<void>;
100
+ /** Default 120_000. */
101
+ readonly timeoutMs?: number;
102
+ /** Default: "Run this?\n<question>\nReply /approve, /approve always or /deny within <n> s." */
103
+ format?(question: string, timeoutMs: number): string;
104
+ }
105
+ /** An approver: a hook that reads the owner's answers and `ask` to put a question to them. */
106
+ interface ChatApprover {
107
+ /** Register in the runner's hooks; it blocks `/approve`, `/approve always` and `/deny`. */
108
+ readonly hook: GatewayHook;
109
+ /** Asks in the conversation and waits. Resolves `deny` on silence, send failure or no open conversation. */
110
+ ask(conversation: string, question: string): Promise<{
111
+ readonly answer: ApprovalAnswer;
112
+ readonly by?: string;
113
+ }>;
114
+ hasPending(event: MessageEvent): boolean;
115
+ }
116
+ /** Asks an owner in the chat to `/approve`, `/approve always` or `/deny`, and waits for the answer. */
117
+ declare function createChatApprover(options: ChatApproverOptions): ChatApprover;
118
+
119
+ /**
120
+ * Structurally equal to `@theokit/agents`' `DeliverPort`; no dependency on `@theokit/agents`.
121
+ *
122
+ * @public
123
+ */
124
+ type GatewayDeliverPort = (target: {
125
+ readonly platform: string;
126
+ readonly channelId: string;
127
+ }, text: string) => Promise<{
128
+ ok: boolean;
129
+ error?: {
130
+ code: string;
131
+ };
132
+ }>;
133
+ /**
134
+ * Adapts gateway adapters to a scheduler's deliver port. `adapters` is read on every send, so a
135
+ * platform that connected later is reached. Text is masked with `options.secrets`, rendered for the
136
+ * platform and sent with `deliverText`. Failures are codes: `not_started` (no adapter for the
137
+ * platform), the adapter's refusal code, or `adapter_threw`.
138
+ *
139
+ * @public
140
+ */
141
+ declare function gatewayDeliverPort(adapters: () => Iterable<BasePlatformAdapter>, options?: {
142
+ secrets?: ReadonlyArray<string>;
143
+ }): GatewayDeliverPort;
144
+ /**
145
+ * Parses `"<platform>:<channelId>"`, split at the first colon, so a channel id may contain more
146
+ * colons (Matrix room ids). Throws `GatewayConfigurationError` with code `invalid_channel_target`
147
+ * when a part is missing; the message never quotes the channel id.
148
+ *
149
+ * @public
150
+ */
151
+ declare function parseChannelTarget(spec: string): {
152
+ platform: PlatformName;
153
+ channelId: string;
154
+ };
155
+
156
+ /**
157
+ * Renders `text` for the adapter's platform and sends it. Resolves `undefined` on success, or a
158
+ * short failure code: the adapter's refusal code, or the thrown error's name. Never a message
159
+ * or an id.
160
+ *
161
+ * @public
162
+ */
163
+ declare function deliverText(adapter: BasePlatformAdapter, channelId: string, text: string, channelType?: "dm" | "group"): Promise<string | undefined>;
164
+
165
+ /**
166
+ * A turn that failed. Carries the platform and the SDK error code only: never the prompt, the
167
+ * answer or an error message from the model.
168
+ *
169
+ * @public
170
+ */
171
+ declare class AgentTurnError extends Error {
172
+ readonly platform: string;
173
+ readonly code: string;
174
+ constructor(platform: string, code: string);
175
+ }
176
+
177
+ /**
178
+ * Wraps untrusted text in a named tag, escaping a forged closing tag (`</tag`, any case) so the
179
+ * body cannot end the frame early. Attribute values are escaped too. Throws `TypeError` when `tag`
180
+ * or an attribute name is not a plain name.
181
+ *
182
+ * @public
183
+ */
184
+ declare function frameUntrusted(tag: string, body: string, attributes?: Record<string, string>): string;
185
+
186
+ /**
187
+ * Same shape as theokit/server/webhook `VerifyFn`, declared here structurally.
188
+ *
189
+ * @public
190
+ */
191
+ type TriggerVerify = (request: Request) => Promise<{
192
+ readonly ok: boolean;
193
+ }>;
194
+ /**
195
+ * What `createTrigger` needs: how to verify, where the answer goes, and which agent runs.
196
+ *
197
+ * @public
198
+ */
199
+ interface TriggerOptions {
200
+ readonly name: string;
201
+ readonly verify: TriggerVerify;
202
+ /** The adapter and channel the answer goes to; undefined adapter means "not started". */
203
+ deliverTo(): {
204
+ readonly adapter: BasePlatformAdapter | undefined;
205
+ readonly channelId: string;
206
+ };
207
+ /** A fresh agent per run; released after the run. */
208
+ agent(): Promise<AgentLease>;
209
+ /** Instructions placed before the framed body. */
210
+ readonly instructions?: string;
211
+ /** Header carrying the delivery id. Default "x-delivery-id"; GitHub users pass "x-github-delivery". */
212
+ readonly dedupeHeader?: string;
213
+ /** How many delivery ids are remembered, oldest dropped first. Default 1000. */
214
+ readonly rememberDeliveries?: number;
215
+ /**
216
+ * Failure codes, besides a built-in list, that may be written as they are. Any other code from
217
+ * the agent or the adapter is written as `unknown`, because a code can echo request data.
218
+ */
219
+ readonly failureCodes?: ReadonlyArray<string>;
220
+ /** Exact values masked out of the reply. */
221
+ readonly secrets?: ReadonlyArray<string>;
222
+ /** Receives one line per failure: a code only, never the body or headers. Default: none. */
223
+ readonly write?: (line: string) => void;
224
+ }
225
+ /**
226
+ * A webhook handler that runs an agent on each new signed delivery.
227
+ *
228
+ * @public
229
+ */
230
+ interface Trigger {
231
+ handle(request: Request): Promise<Response>;
232
+ /** Resolves when every run started so far has ended (for shutdown and tests). */
233
+ idle(): Promise<void>;
234
+ }
235
+ /**
236
+ * Builds a trigger: verifies the request (401 on failure, nothing read), refuses a delivery id
237
+ * over 256 chars (400), answers 503 while the reply adapter is not started (the id is not
238
+ * remembered, so the retry runs), 200 for an id seen before, and otherwise 202 while one run
239
+ * starts in the background. The answer is masked and sent to the channel; a failed run or
240
+ * undelivered reply is written as one line holding a code.
241
+ *
242
+ * @public
243
+ */
244
+ declare function createTrigger(options: TriggerOptions): Trigger;
245
+
246
+ export { type AgentHandlerOptions, type AgentLease, type AgentTextResult, AgentTurnError, type ApprovalAnswer, type ChatApprover, type ChatApproverOptions, type GatewayDeliverPort, type Trigger, type TriggerOptions, type TriggerVerify, type TurnAgent, createAgentHandler, createChatApprover, createTrigger, deliverText, frameUntrusted, gatewayDeliverPort, parseChannelTarget, runAgentText };