@agentchatme/agent-core 0.4.0 → 0.5.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,97 @@
1
+ import {
2
+ clientIdentityOf,
3
+ killProcessTree,
4
+ spawnCommand
5
+ } from "./chunk-AFDD53DD.js";
6
+
7
+ // src/version.ts
8
+ var VERSION = "0.5.0";
9
+
10
+ // src/integration/mcp-probe.ts
11
+ import { integration as kit } from "agentchatme";
12
+ var HOSTED_MCP_PATH = kit.HOSTED_MCP_PATH;
13
+ function hostedMcpUrl(apiBase) {
14
+ return kit.hostedMcpUrl(apiBase);
15
+ }
16
+ async function probeHostedMcp(params) {
17
+ return kit.probeHostedTools({
18
+ apiBase: params.apiBase,
19
+ apiKey: params.apiKey,
20
+ clientIdentity: clientIdentityOf(params.client),
21
+ ...params.timeoutMs !== void 0 ? { timeoutMs: params.timeoutMs } : {},
22
+ ...params.fetch !== void 0 ? { fetch: params.fetch } : {}
23
+ });
24
+ }
25
+
26
+ // src/util/probe.ts
27
+ var PROBE_KILL_WAIT_MS = 5e3;
28
+ var MAX_OUTPUT = 64 * 1024;
29
+ function runProbe(command, args, options) {
30
+ return new Promise((resolve) => {
31
+ let child;
32
+ try {
33
+ child = spawnCommand(command, [...args], {
34
+ ...options.env !== void 0 ? { env: options.env } : {},
35
+ ...options.cwd !== void 0 ? { cwd: options.cwd } : {},
36
+ stdio: ["ignore", "pipe", "pipe"],
37
+ // Its own process group on POSIX, so the whole tree can be killed.
38
+ detached: process.platform !== "win32",
39
+ windowsHide: true
40
+ });
41
+ } catch (err) {
42
+ resolve({ error: err instanceof Error ? err : new Error(String(err)), status: null, stdout: "", stderr: "", timedOut: false });
43
+ return;
44
+ }
45
+ const proc = child;
46
+ let stdout = "";
47
+ let stderr = "";
48
+ let timedOut = false;
49
+ let stopped = false;
50
+ let finished = false;
51
+ let giveUp = null;
52
+ const finish = (result) => {
53
+ if (finished) return;
54
+ finished = true;
55
+ clearTimeout(timer);
56
+ if (giveUp !== null) clearTimeout(giveUp);
57
+ resolve(result);
58
+ };
59
+ proc.stdout?.on("data", (chunk) => {
60
+ if (stdout.length < MAX_OUTPUT) stdout += chunk.toString("utf-8");
61
+ });
62
+ proc.stderr?.on("data", (chunk) => {
63
+ if (stderr.length < MAX_OUTPUT) stderr += chunk.toString("utf-8");
64
+ });
65
+ const stop = (error, byTimeout) => {
66
+ if (timedOut || finished) return;
67
+ timedOut = byTimeout;
68
+ stopped = true;
69
+ killProcessTree(proc, "SIGKILL");
70
+ giveUp = setTimeout(() => {
71
+ proc.stdout?.destroy();
72
+ proc.stderr?.destroy();
73
+ finish({ error, status: null, stdout, stderr, timedOut });
74
+ }, PROBE_KILL_WAIT_MS);
75
+ proc.once("close", () => finish({ error, status: null, stdout, stderr, timedOut }));
76
+ };
77
+ const timer = setTimeout(() => stop(new Error(`${command} ${args.join(" ")} did not answer within ${Math.round(options.timeoutMs / 1e3)} s`), true), options.timeoutMs);
78
+ const onAbort = () => stop(new Error(`${command} ${args.join(" ")} was stopped`), false);
79
+ if (options.signal?.aborted) onAbort();
80
+ else options.signal?.addEventListener("abort", onAbort, { once: true });
81
+ proc.on("error", (err) => finish({ error: err, status: null, stdout, stderr, timedOut }));
82
+ proc.on("close", (code) => {
83
+ options.signal?.removeEventListener("abort", onAbort);
84
+ if (!stopped) finish({ status: code, stdout, stderr, timedOut });
85
+ });
86
+ });
87
+ }
88
+
89
+ export {
90
+ VERSION,
91
+ HOSTED_MCP_PATH,
92
+ hostedMcpUrl,
93
+ probeHostedMcp,
94
+ PROBE_KILL_WAIT_MS,
95
+ runProbe
96
+ };
97
+ //# sourceMappingURL=chunk-UE7DKW3C.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/version.ts","../src/integration/mcp-probe.ts","../src/util/probe.ts"],"sourcesContent":["/** Published package version, kept in lockstep with package.json by tests. */\nexport const VERSION = '0.5.0'\n","import { integration as kit } from 'agentchatme'\nimport { clientIdentityOf, type IntegrationClient } from '../client-identity.js'\n\n// ─── Can this key reach the hosted tools? ───────────────────────────────────\n//\n// `status` and `doctor` ask the SDK kit's `probeHostedTools`: one MCP\n// `initialize` over Streamable HTTP with the bearer key — the same first\n// request a runtime makes on connect — then `tools/list`, which must show the\n// tools a run needs (`agentchat_inbox`, `agentchat_decide`). A 401 means the\n// key does not authenticate; a transport error means the endpoint is not\n// reachable from here. No tool is called.\n\nexport const HOSTED_MCP_PATH = kit.HOSTED_MCP_PATH\n\nexport function hostedMcpUrl(apiBase: string): string {\n return kit.hostedMcpUrl(apiBase)\n}\n\nexport interface McpProbeResult {\n readonly ok: boolean\n readonly status?: number\n readonly serverName?: string\n readonly serverVersion?: string\n readonly protocolVersion?: string\n /** Every tool the server listed for this key. */\n readonly tools?: readonly string[]\n /** Tools a run needs that were not listed. */\n readonly missing?: readonly string[]\n readonly error?: string\n}\n\nexport async function probeHostedMcp(params: {\n apiKey: string\n apiBase: string\n /** How this integration identifies to the server. */\n client: IntegrationClient\n /**\n * Accepted for compatibility and ignored: the probe identifies as `client`\n * (headers and `clientInfo` alike), so the server's analytics see the\n * integration, never a free-text name it would file as unknown.\n */\n clientName?: string\n /** Accepted for compatibility and ignored (see `clientName`). */\n clientVersion?: string\n timeoutMs?: number\n fetch?: typeof fetch\n}): Promise<McpProbeResult> {\n return kit.probeHostedTools({\n apiBase: params.apiBase,\n apiKey: params.apiKey,\n clientIdentity: clientIdentityOf(params.client),\n ...(params.timeoutMs !== undefined ? { timeoutMs: params.timeoutMs } : {}),\n ...(params.fetch !== undefined ? { fetch: params.fetch } : {}),\n })\n}\n","import { killProcessTree } from '../integration/spawn-run.js'\nimport { spawnCommand } from './spawn.js'\n\n// ─── A short command whose answer we need (`--version`, a sign-in check) ────\n//\n// Was `spawnSync` with a timeout, which on timeout kills only the direct child:\n// on Windows the npm `.cmd` shim (the real process under it keeps running), and\n// the npm launcher of a runtime that starts its native binary as a child. A sync\n// spawn then also waits for those survivors to close the output pipes it reads —\n// blocking the whole daemon, socket included. A probe is therefore async: on\n// timeout the whole tree is killed (its process group on POSIX, `taskkill /T /F`\n// on Windows), its exit is waited for, and a tree that will not die is given up\n// on after a bound — the probe always answers.\n\nexport interface ProbeResult {\n /** Why it did not answer: it could not be started, or it timed out. */\n readonly error?: Error\n readonly status: number | null\n readonly stdout: string\n readonly stderr: string\n readonly timedOut: boolean\n}\n\nexport interface ProbeOptions {\n readonly env?: NodeJS.ProcessEnv\n readonly timeoutMs: number\n readonly cwd?: string\n /** Aborting it stops the probe as a timeout would (its tree killed, its exit waited for). */\n readonly signal?: AbortSignal\n}\n\n/** After a probe is killed: how long its exit is waited for before it is given up on. */\nexport const PROBE_KILL_WAIT_MS = 5_000\nconst MAX_OUTPUT = 64 * 1024\n\nexport function runProbe(command: string, args: readonly string[], options: ProbeOptions): Promise<ProbeResult> {\n return new Promise((resolve) => {\n let child: ReturnType<typeof spawnCommand>\n try {\n child = spawnCommand(command, [...args], {\n ...(options.env !== undefined ? { env: options.env } : {}),\n ...(options.cwd !== undefined ? { cwd: options.cwd } : {}),\n stdio: ['ignore', 'pipe', 'pipe'],\n // Its own process group on POSIX, so the whole tree can be killed.\n detached: process.platform !== 'win32',\n windowsHide: true,\n })\n } catch (err) {\n resolve({ error: err instanceof Error ? err : new Error(String(err)), status: null, stdout: '', stderr: '', timedOut: false })\n return\n }\n const proc = child\n let stdout = ''\n let stderr = ''\n let timedOut = false\n let stopped = false\n let finished = false\n let giveUp: NodeJS.Timeout | null = null\n const finish = (result: ProbeResult): void => {\n if (finished) return\n finished = true\n clearTimeout(timer)\n if (giveUp !== null) clearTimeout(giveUp)\n resolve(result)\n }\n proc.stdout?.on('data', (chunk: Buffer) => {\n if (stdout.length < MAX_OUTPUT) stdout += chunk.toString('utf-8')\n })\n proc.stderr?.on('data', (chunk: Buffer) => {\n if (stderr.length < MAX_OUTPUT) stderr += chunk.toString('utf-8')\n })\n const stop = (error: Error, byTimeout: boolean): void => {\n if (timedOut || finished) return\n timedOut = byTimeout\n stopped = true\n killProcessTree(proc, 'SIGKILL')\n // Its exit (every pipe closed) is the answer; a tree that will not die is given up on.\n giveUp = setTimeout(() => {\n proc.stdout?.destroy()\n proc.stderr?.destroy()\n finish({ error, status: null, stdout, stderr, timedOut })\n }, PROBE_KILL_WAIT_MS)\n proc.once('close', () => finish({ error, status: null, stdout, stderr, timedOut }))\n }\n const timer = setTimeout(() => stop(new Error(`${command} ${args.join(' ')} did not answer within ${Math.round(options.timeoutMs / 1000)} s`), true), options.timeoutMs)\n const onAbort = (): void => stop(new Error(`${command} ${args.join(' ')} was stopped`), false)\n if (options.signal?.aborted) onAbort()\n else options.signal?.addEventListener('abort', onAbort, { once: true })\n proc.on('error', (err) => finish({ error: err, status: null, stdout, stderr, timedOut }))\n proc.on('close', (code) => {\n options.signal?.removeEventListener('abort', onAbort)\n if (!stopped) finish({ status: code, stdout, stderr, timedOut })\n })\n })\n}\n"],"mappings":";;;;;;;AACO,IAAM,UAAU;;;ACDvB,SAAS,eAAe,WAAW;AAY5B,IAAM,kBAAkB,IAAI;AAE5B,SAAS,aAAa,SAAyB;AACpD,SAAO,IAAI,aAAa,OAAO;AACjC;AAeA,eAAsB,eAAe,QAeT;AAC1B,SAAO,IAAI,iBAAiB;AAAA,IAC1B,SAAS,OAAO;AAAA,IAChB,QAAQ,OAAO;AAAA,IACf,gBAAgB,iBAAiB,OAAO,MAAM;AAAA,IAC9C,GAAI,OAAO,cAAc,SAAY,EAAE,WAAW,OAAO,UAAU,IAAI,CAAC;AAAA,IACxE,GAAI,OAAO,UAAU,SAAY,EAAE,OAAO,OAAO,MAAM,IAAI,CAAC;AAAA,EAC9D,CAAC;AACH;;;ACtBO,IAAM,qBAAqB;AAClC,IAAM,aAAa,KAAK;AAEjB,SAAS,SAAS,SAAiB,MAAyB,SAA6C;AAC9G,SAAO,IAAI,QAAQ,CAAC,YAAY;AAC9B,QAAI;AACJ,QAAI;AACF,cAAQ,aAAa,SAAS,CAAC,GAAG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AG,kBAAkB;AACrB,WAAK,KAAK,SAAS,MAAM,OAAO,EAAE,OAAO,QAAQ,MAAM,QAAQ,QAAQ,SAAS,CAAC,CAAC;AAAA,IACpF;AACA,UAAM,QAAQ,WAAW,MAAM,KAAK,IAAI,MAAM,GAAG,OAAO,IAAI,KAAK,KAAK,GAAG,CAAC,0BAA0B,KAAK,MAAM,QAAQ,YAAY,GAAI,CAAC,IAAI,GAAG,IAAI,GAAG,QAAQ,SAAS;AACvK,UAAM,UAAU,MAAY,KAAK,IAAI,MAAM,GAAG,OAAO,IAAI,KAAK,KAAK,GAAG,CAAC,cAAc,GAAG,KAAK;AAC7F,QAAI,QAAQ,QAAQ,QAAS,SAAQ;AAAA,QAChC,SAAQ,QAAQ,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;AACtE,SAAK,GAAG,SAAS,CAAC,QAAQ,OAAO,EAAE,OAAO,KAAK,QAAQ,MAAM,QAAQ,QAAQ,SAAS,CAAC,CAAC;AACxF,SAAK,GAAG,SAAS,CAAC,SAAS;AACzB,cAAQ,QAAQ,oBAAoB,SAAS,OAAO;AACpD,UAAI,CAAC,QAAS,QAAO,EAAE,QAAQ,MAAM,QAAQ,QAAQ,SAAS,CAAC;AAAA,IACjE,CAAC;AAAA,EACH,CAAC;AACH;","names":[]}
@@ -1,6 +1,6 @@
1
- import { I as IntegrationClient, M as ManualFetch, a as IntegrationStatus, S as SocketState } from './served-manual-DZmEak4_.js';
2
- import { R as RunnerSource, a as RunProfile, b as RunRunner, c as RunOutcome } from './runner-BzgsiS3V.js';
3
- export { d as RunKind, e as RunOutcomeState, f as RunPreflight, g as RunRequest, h as RunWake, i as RunnerFactory, j as RunnerIdentity } from './runner-BzgsiS3V.js';
1
+ import { I as IntegrationClient, L as LeaseOptions, M as ManualFetch, a as IntegrationStatus, b as IntegrationRunsFailing, S as SocketState } from './served-manual-2rjsjJFD.js';
2
+ import { R as RunnerSource, a as RunProfile, b as RunRunner, c as RunOutcome } from './runner-DYVqz_9P.js';
3
+ export { d as RunKind, e as RunOutcomeState, f as RunPreflight, g as RunRequest, h as RunWake, i as RunnerFactory, j as RunnerIdentity } from './runner-DYVqz_9P.js';
4
4
  import { AgentChatClient, RealtimeClient, BlockedInfo, RealtimeState } from 'agentchatme';
5
5
  import 'zod';
6
6
 
@@ -39,6 +39,24 @@ interface RunIntegrationOpts {
39
39
  credentialsFromHomeOnly?: boolean;
40
40
  /** See `IntegrationOptions.dismissIgnoredInvites` (default true). */
41
41
  dismissIgnoredInvites?: boolean;
42
+ /** Test seam: while serving, how often to look again (5 s; the backoff after failed starts grows from it). */
43
+ pollMs?: number;
44
+ /** Test seam: the loop's own tick, how soon it notices a nudge (250 ms). */
45
+ tickMs?: number;
46
+ /** Test seams: `IntegrationOptions.quietMs`, `maxMs` and `paceMs` (when a wake's run starts). */
47
+ quietMs?: number;
48
+ maxMs?: number;
49
+ paceMs?: number;
50
+ /** Test seam: while another daemon serves this agent, how often to look again (30 s). */
51
+ standbyPollMs?: number;
52
+ /** Test seam: `IntegrationOptions.runtimeRecheckMs`. */
53
+ runtimeRecheckMs?: number;
54
+ /** Test seam: after giving the agent up, when to look again (60 s; 5 min after a refused key). */
55
+ unservableRecheckMs?: number;
56
+ /** Test seam: the agent and home leases' timing (`LeaseOptions`). */
57
+ lease?: LeaseOptions;
58
+ /** Test seam: how long a give-up recheck waits for the runtime's preflight (`PREFLIGHT_DEADLINE_MS`). */
59
+ preflightDeadlineMs?: number;
42
60
  }
43
61
  /**
44
62
  * Run the integration daemon. Returns only on a condition that makes running
@@ -106,6 +124,10 @@ interface IntegrationOptions {
106
124
  readonly budgetMs: number;
107
125
  /** Injectable for tests; past `budgetMs` plus this a runner that has not returned is abandoned. */
108
126
  readonly runnerDeadlineSlackMs?: number;
127
+ /** Injectable for tests; `RUNTIME_RECHECK_MS`. */
128
+ readonly runtimeRecheckMs?: number;
129
+ /** What the supervisor adds to every status this integration writes (its locks' renewal errors). */
130
+ readonly statusExtra?: () => Partial<IntegrationStatus>;
109
131
  /** Injectable for tests; defaults to an SDK client for `cfg`. */
110
132
  readonly api?: AgentChatClient;
111
133
  /** Injectable for tests: the socket (built with `ackOnReceipt` and the v1 capabilities otherwise). */
@@ -141,6 +163,16 @@ declare class Integration {
141
163
  private statusTimer;
142
164
  private socket;
143
165
  private lastError;
166
+ /** When the first run that did not get done since the last good one ended; null while runs succeed. */
167
+ private failingSince;
168
+ /** Runs that did not get done since then. */
169
+ private failingRuns;
170
+ /** What the runtime's own check says while runs fail (status `runs_failing`); null when it has not failed one. */
171
+ private runsFailing;
172
+ private lastRecheckAt;
173
+ private recheckInFlight;
174
+ /** Aborts a runtime check in flight when the integration stops (its probes are killed, not left running). */
175
+ private readonly recheckAbort;
144
176
  private stopping;
145
177
  private stopped;
146
178
  private invites;
@@ -171,6 +203,29 @@ declare class Integration {
171
203
  wake(): void;
172
204
  snapshot(): IntegrationStatus;
173
205
  private startRun;
206
+ /**
207
+ * A run that did not get done may be the runtime itself (signed out, the
208
+ * binary gone, a flag an upgrade dropped): checked again, at most once per
209
+ * `RUNTIME_RECHECK_MS`, and said in status until a run succeeds. Wakes keep
210
+ * starting runs meanwhile — each is the quickest way back — and are counted.
211
+ */
212
+ private noteRunHealth;
213
+ private recheckRuntime;
214
+ /**
215
+ * Whether this integration can serve its agent: not while the server refuses
216
+ * its key (socket `blocked`: rotated by `recover` elsewhere, revoked), nor
217
+ * while runs fail for a runtime reason (`runs_failing`). The supervisor then
218
+ * gives the agent up so a healthy listener for it can serve.
219
+ */
220
+ health(): {
221
+ ok: true;
222
+ } | {
223
+ ok: false;
224
+ reason: string;
225
+ runsFailing: IntegrationRunsFailing | null;
226
+ };
227
+ /** Test seam: resolves when a runtime check started by a failed run has finished. */
228
+ runtimeCheckDone(): Promise<void>;
174
229
  private onEvent;
175
230
  private writeStatus;
176
231
  }