@synadia-ai/agent-fabric-claude-code 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.
package/dist/index.js ADDED
@@ -0,0 +1,248 @@
1
+ import { SP_VARS, spBinary as spBinary$1, resolveScratchPad, resolveEdgeSubject, fabricTracing, loopGuard, exportScratchPad, ServedPromptEnv, ScratchPadHandOn, bindActiveTrace, activeTrace, servedPublisher, READS_REFERENCES_KEY, spPort as spPort$1 } from '@synadia-ai/agent-fabric';
2
+ export { SCRATCHPAD_OPTION, SP_VARS, ScratchPadHandOn } from '@synadia-ai/agent-fabric';
3
+ import { NatsAgentError } from '@synadia-ai/agents';
4
+ import { mkdirSync, writeFileSync, renameSync, rmSync } from 'fs';
5
+ import { join, dirname } from 'path';
6
+ import { fileURLToPath } from 'url';
7
+
8
+ // src/extension.ts
9
+ var SKILL_DIR = fileURLToPath(new URL("../skills/scratchpad", import.meta.url));
10
+ var SP_ENV_FILE_VAR = "SP_ENV_FILE";
11
+ function spBinary(env) {
12
+ return spBinary$1(env, SKILL_DIR);
13
+ }
14
+ function spPort(settings, creator, env) {
15
+ return spPort$1(settings, creator, env, SKILL_DIR);
16
+ }
17
+ function spEnvFilePath(stateDir, env, parentPid = process.ppid) {
18
+ const pid = env["CLAUDE_PID"];
19
+ return join(
20
+ stateDir,
21
+ "agent-fabric",
22
+ `${pid !== void 0 && /^\d+$/.test(pid) ? pid : String(parentPid)}.env`
23
+ );
24
+ }
25
+ var NAMES = new Set(Object.values(SP_VARS));
26
+ var SpEnvFile = class {
27
+ constructor(path) {
28
+ this.path = path;
29
+ }
30
+ path;
31
+ /** What the shared pieces set and clear; `write()` puts it in the file. */
32
+ vars = {};
33
+ /**
34
+ * The file, whole, through a rename, so `scripts/sp` reads one state or
35
+ * the next. A value with a line break could not be read back, so it is
36
+ * left out. Throws what the file system throws.
37
+ */
38
+ write() {
39
+ let text = "";
40
+ for (const [name, value] of Object.entries(this.vars)) {
41
+ if (!NAMES.has(name) || value === void 0 || /[\r\n]/.test(value)) continue;
42
+ text += `${name}=${value}
43
+ `;
44
+ }
45
+ mkdirSync(dirname(this.path), { recursive: true, mode: 448 });
46
+ const staging = `${this.path}.${process.pid}.tmp`;
47
+ writeFileSync(staging, text, { mode: 384 });
48
+ renameSync(staging, this.path);
49
+ }
50
+ /** Removes the file, when the server stops; `scripts/sp` then finds no configuration. */
51
+ remove() {
52
+ rmSync(this.path, { force: true });
53
+ }
54
+ };
55
+
56
+ // src/extension.ts
57
+ var EXTENSION_NAME = "agent-fabric";
58
+ var SERVED_HARNESS = "claude";
59
+ var DEFAULT_STOP_WAIT_MS = 12e4;
60
+ var IDENTITY_OFF_WARNING = `${EXTENSION_NAME}: senderIdentity is off; trace records are signed, so none will be published and each counts as dropped on the heartbeat. Set senderIdentity to signed.`;
61
+ var NO_SESSION_LINE = `${EXTENSION_NAME}: no Claude Code session id known for this prompt, so no served pair; its model calls stand as a harness thread of their own. Are the plugin's hooks registered?`;
62
+ var SESSION_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
63
+ function isClaudeSessionId(value) {
64
+ return typeof value === "string" && SESSION_ID_RE.test(value);
65
+ }
66
+ function stopWaitFrom(options) {
67
+ const value = options["stopWaitMs"];
68
+ if (value === void 0) return DEFAULT_STOP_WAIT_MS;
69
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
70
+ throw new NatsAgentError(`${EXTENSION_NAME}: options.stopWaitMs must be a number of ms \u2265 0`);
71
+ }
72
+ return value;
73
+ }
74
+ async function fabricExtension(ctx, env = process.env) {
75
+ return createFabricExtension(ctx, env, await resolveScratchPad(ctx, env));
76
+ }
77
+ function createFabricExtension(ctx, env = process.env, scratchPad) {
78
+ const edgeSubject = resolveEdgeSubject(ctx.options, env);
79
+ const stopWaitMs = stopWaitFrom(ctx.options);
80
+ const tracing = fabricTracing({ edgeSubject });
81
+ const guard = loopGuard();
82
+ const log = ctx.logger;
83
+ let publisher;
84
+ let currentSession;
85
+ const served = /* @__PURE__ */ new Map();
86
+ const awaitingStop = [];
87
+ const release = (waiting) => {
88
+ const at = awaitingStop.indexOf(waiting);
89
+ if (at >= 0) awaitingStop.splice(at, 1);
90
+ clearTimeout(waiting.timer);
91
+ };
92
+ let warnedIdentityOff = false;
93
+ let spEnv;
94
+ if (scratchPad !== void 0) {
95
+ if (ctx.settings.stateDir !== void 0) {
96
+ spEnv = new SpEnvFile(spEnvFilePath(ctx.settings.stateDir, env));
97
+ } else {
98
+ log.warn(
99
+ `${EXTENSION_NAME}: the plugin names no state directory, so the skill's scripts/sp gets no ScratchPad settings`
100
+ );
101
+ }
102
+ }
103
+ const writeSpEnv = () => {
104
+ if (spEnv === void 0) return;
105
+ try {
106
+ spEnv.write();
107
+ } catch (err) {
108
+ log.warn(`${EXTENSION_NAME}: ScratchPad's settings for scripts/sp: ${String(err)}`);
109
+ }
110
+ };
111
+ if (scratchPad !== void 0 && spEnv !== void 0) {
112
+ exportScratchPad(scratchPad, spEnv.vars);
113
+ writeSpEnv();
114
+ }
115
+ const promptEnv = spEnv !== void 0 ? new ServedPromptEnv(spEnv.vars) : void 0;
116
+ const handOn = scratchPad !== void 0 ? new ScratchPadHandOn() : void 0;
117
+ return {
118
+ name: EXTENSION_NAME,
119
+ // The service: tracing first, so the guard runs inside the scope tracing
120
+ // bound and a malformed pair is refused with 400 before the guard
121
+ // looks; the plugin appends its own (the tools' scope) after these.
122
+ // The ScratchPad extension's, last, remembers the references each
123
+ // served prompt brings, which Claude Code may hand on.
124
+ requestInterceptors: [
125
+ tracing.requestInterceptor,
126
+ guard.requestInterceptor,
127
+ ...handOn !== void 0 ? [handOn.requestInterceptor] : []
128
+ ],
129
+ // The client Claude Code's agent tools prompt through: the edge and the
130
+ // pair, then the waiting mark. Both read the ambient scope, so the
131
+ // order between them does not matter.
132
+ promptInterceptors: [tracing.promptInterceptor, guard.promptInterceptor],
133
+ heartbeatExtras: tracing.heartbeatExtras,
134
+ ...handOn !== void 0 ? {
135
+ // References in Claude Code's `prompt_agent`: granted to a
136
+ // receiver that reads them, removed with a note for any other.
137
+ toolExtensions: [handOn],
138
+ // So a caller's `prompt_agent` hands references to Claude Code.
139
+ metadata: { [READS_REFERENCES_KEY]: "true" }
140
+ } : {},
141
+ started({ agents, service }) {
142
+ if (ctx.settings.senderIdentity !== "signed" && !warnedIdentityOff) {
143
+ warnedIdentityOff = true;
144
+ log.warn(IDENTITY_OFF_WARNING);
145
+ }
146
+ if (edgeSubject !== null) {
147
+ publisher = servedPublisher({ agents, subject: edgeSubject, logger: log });
148
+ }
149
+ log.info(
150
+ `${EXTENSION_NAME}: tracing ${service.subject.prompt}` + (edgeSubject === null ? " (propagate-only: lineage forwarded, no edge or served record published)" : `, edge and served records on ${edgeSubject}`)
151
+ );
152
+ if (scratchPad !== void 0 && handOn !== void 0) {
153
+ if (spEnv !== void 0) {
154
+ spEnv.vars[SP_VARS.creator] = service.subject.prompt;
155
+ writeSpEnv();
156
+ }
157
+ const port = spPort(scratchPad, service.subject.prompt, env);
158
+ if (port !== void 0) handOn.start({ scratchPad: port, agents, service, logger: log });
159
+ else
160
+ log.warn(
161
+ `${EXTENSION_NAME}: no sp for this platform (set SCRATCHPAD_BIN); references in prompt_agent are not handed on, and grant requests not answered`
162
+ );
163
+ log.info(
164
+ `${EXTENSION_NAME}: ScratchPad volume ${scratchPad.volume}` + (scratchPad.dir !== void 0 ? `, workspace ${scratchPad.dir}` : ", no workspace") + (spEnv !== void 0 ? `, for the skill's scripts/sp through ${spEnv.path}` : "")
165
+ );
166
+ }
167
+ },
168
+ async stopping() {
169
+ for (const waiting of [...awaitingStop]) {
170
+ release(waiting);
171
+ waiting.turn.settle("ok", waiting.repliedAtMs);
172
+ }
173
+ for (const [id, entry] of served) {
174
+ served.delete(id);
175
+ entry.turn?.settle("error", void 0, "shutdown");
176
+ }
177
+ spEnv?.remove();
178
+ await publisher?.flush();
179
+ },
180
+ events: {
181
+ sessionStarted(sessionId) {
182
+ if (isClaudeSessionId(sessionId)) currentSession = sessionId;
183
+ },
184
+ promptAccepted(request) {
185
+ const scope = activeTrace();
186
+ if (promptEnv !== void 0) {
187
+ promptEnv.enter(request, scope);
188
+ writeSpEnv();
189
+ }
190
+ if (scope === void 0) return;
191
+ const named = request.sessionId ?? currentSession;
192
+ const sessionId = isClaudeSessionId(named) ? named : void 0;
193
+ let turn;
194
+ if (sessionId === void 0) {
195
+ log.warn(NO_SESSION_LINE);
196
+ } else {
197
+ turn = publisher?.beginTurn(scope, SERVED_HARNESS);
198
+ turn?.bind(sessionId);
199
+ }
200
+ served.set(request.id, { request, scope, sessionId, turn });
201
+ },
202
+ promptEnded(request, outcome, atMs, reason) {
203
+ const entry = served.get(request.id);
204
+ served.delete(request.id);
205
+ if (promptEnv !== void 0) {
206
+ promptEnv.leave(request);
207
+ const open = [...served.values()].at(-1);
208
+ if (open !== void 0) promptEnv.enter(open.request, open.scope);
209
+ writeSpEnv();
210
+ }
211
+ if (entry === void 0) return;
212
+ const { turn, sessionId } = entry;
213
+ if (turn === void 0 || sessionId === void 0) return;
214
+ if (outcome !== "ok" || reason === "final_text") {
215
+ turn.settle(outcome, atMs, reason);
216
+ return;
217
+ }
218
+ const waiting = {
219
+ sessionId,
220
+ turn,
221
+ repliedAtMs: atMs,
222
+ timer: setTimeout(() => {
223
+ release(waiting);
224
+ turn.settle("ok", atMs);
225
+ }, stopWaitMs)
226
+ };
227
+ waiting.timer.unref?.();
228
+ awaitingStop.push(waiting);
229
+ },
230
+ turnStopped(sessionId, atMs) {
231
+ for (const waiting of [...awaitingStop]) {
232
+ if (sessionId !== void 0 && waiting.sessionId !== sessionId) continue;
233
+ if (waiting.repliedAtMs >= atMs) continue;
234
+ release(waiting);
235
+ waiting.turn.settle("ok", atMs);
236
+ }
237
+ },
238
+ aroundToolCall(request, _toolName, run) {
239
+ const scope = request === void 0 ? void 0 : served.get(request.id)?.scope;
240
+ return scope === void 0 ? run() : bindActiveTrace(scope, () => guard.aroundToolCall(scope, run));
241
+ }
242
+ }
243
+ };
244
+ }
245
+
246
+ export { DEFAULT_STOP_WAIT_MS, EXTENSION_NAME, IDENTITY_OFF_WARNING, NO_SESSION_LINE, SERVED_HARNESS, SP_ENV_FILE_VAR, SpEnvFile, createFabricExtension, fabricExtension as default, fabricExtension, isClaudeSessionId, spBinary, spEnvFilePath };
247
+ //# sourceMappingURL=index.js.map
248
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/scratchpad.ts","../src/extension.ts"],"names":["sharedSpBinary","sharedSpPort","SP_VARS"],"mappings":";;;;;;;;AAuCO,IAAM,YAAY,aAAA,CAAc,IAAI,IAAI,sBAAA,EAAwB,MAAA,CAAA,IAAA,CAAY,GAAG,CAAC,CAAA;AAGhF,IAAM,eAAA,GAAkB;AAGxB,SAAS,SAAS,GAAA,EAA6D;AACpF,EAAA,OAAOA,UAAA,CAAe,KAAK,SAAS,CAAA;AACtC;AAGO,SAAS,MAAA,CACd,QAAA,EACA,OAAA,EACA,GAAA,EACwB;AACxB,EAAA,OAAOC,QAAA,CAAa,QAAA,EAAU,OAAA,EAAS,GAAA,EAAK,SAAS,CAAA;AACvD;AAQO,SAAS,aAAA,CACd,QAAA,EACA,GAAA,EACA,SAAA,GAAoB,QAAQ,IAAA,EACpB;AACR,EAAA,MAAM,GAAA,GAAM,IAAI,YAAY,CAAA;AAC5B,EAAA,OAAO,IAAA;AAAA,IACL,QAAA;AAAA,IACA,cAAA;AAAA,IACA,CAAA,EAAG,GAAA,KAAQ,MAAA,IAAa,OAAA,CAAQ,IAAA,CAAK,GAAG,CAAA,GAAI,GAAA,GAAM,MAAA,CAAO,SAAS,CAAC,CAAA,IAAA;AAAA,GACrE;AACF;AAGA,IAAM,QAA6B,IAAI,GAAA,CAAI,MAAA,CAAO,MAAA,CAAO,OAAO,CAAC,CAAA;AAM1D,IAAM,YAAN,MAAgB;AAAA,EAIrB,YAAqB,IAAA,EAA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CAAQ,IAAA,CAAK,MAAA,CAAO,IAAA,EAAM,IAAI,CAAA;AAAA,QAChC;AAAA,MACF,CAAA;AAAA,MAEA,cAAA,CAAe,OAAA,EAAoC,SAAA,EAAW,GAAA,EAAK;AACjE,QAAA,MAAM,KAAA,GAAQ,YAAY,MAAA,GAAY,MAAA,GAAY,OAAO,GAAA,CAAI,OAAA,CAAQ,EAAE,CAAA,EAAG,KAAA;AAC1E,QAAA,OAAO,KAAA,KAAU,MAAA,GACb,GAAA,EAAI,GACJ,eAAA,CAAgB,KAAA,EAAO,MAAM,KAAA,CAAM,cAAA,CAAe,KAAA,EAAO,GAAG,CAAC,CAAA;AAAA,MACnE;AAAA;AACF,GACF;AACF","file":"index.js","sourcesContent":["// ScratchPad for Claude Code's model (`docs/plugins.md` §9): the pieces every\n// add-on shares, from the fabric package (`plugin-scratchpad.ts` there), with\n// this package's copy of the skill (`skills/scratchpad`, installed by\n// `npm run build:sp` from `plugins/scratchpad-skill`), and the one piece\n// Claude Code needs of its own: the file the variables go to.\n//\n// This module runs in the NATS channel plugin's MCP server, a child of\n// Claude Code and a sibling of the Bash tool's processes, so nothing it sets\n// in its own environment reaches `scripts/sp` (§9.4). So it keeps the\n// variables in a file, `<state dir>/agent-fabric/<CLAUDE_PID>.env`, rewritten\n// whole on every change, and this package's own Claude Code hook\n// (`hooks/session-start.sh`, at SessionStart) names that file to the Bash\n// tool as `SP_ENV_FILE`, which `scripts/sp` reads on every call. So the\n// served prompt's trace and caller reach each call, per turn, with nothing\n// from the operator but loading this package as a plugin, which the skill\n// needs anyway.\n\nimport { mkdirSync, renameSync, rmSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport {\n spBinary as sharedSpBinary,\n spPort as sharedSpPort,\n SP_VARS,\n type ScratchPad,\n type ScratchPadSettings,\n} from \"@synadia-ai/agent-fabric\";\n\nexport {\n exportScratchPad,\n resolveScratchPad,\n SCRATCHPAD_OPTION,\n ScratchPadHandOn,\n ServedPromptEnv,\n SP_VARS,\n type ScratchPadSettings,\n} from \"@synadia-ai/agent-fabric\";\n\n/** This package's skill directory: `src/` in the tests, `dist/` when installed, one level below it. */\nexport const SKILL_DIR = fileURLToPath(new URL(\"../skills/scratchpad\", import.meta.url));\n\n/** The variable that names the file to `scripts/sp`, set by the package's hook. */\nexport const SP_ENV_FILE_VAR = \"SP_ENV_FILE\";\n\n/** The sp binary this package ships for this machine, or `SCRATCHPAD_BIN`. */\nexport function spBinary(env: Record<string, string | undefined>): string | undefined {\n return sharedSpBinary(env, SKILL_DIR);\n}\n\n/** The ScratchPad port over this package's sp, for the extension's grants. */\nexport function spPort(\n settings: ScratchPadSettings,\n creator: string,\n env: Record<string, string | undefined>,\n): ScratchPad | undefined {\n return sharedSpPort(settings, creator, env, SKILL_DIR);\n}\n\n/**\n * The file for the Claude Code process this server runs under:\n * `<stateDir>/agent-fabric/<pid>.env`, where the hook looks for it. The pid\n * is `CLAUDE_PID`, which Claude Code hands its hooks and its MCP servers\n * alike, else the parent's, as the plugin keys its own files.\n */\nexport function spEnvFilePath(\n stateDir: string,\n env: Record<string, string | undefined>,\n parentPid: number = process.ppid,\n): string {\n const pid = env[\"CLAUDE_PID\"];\n return join(\n stateDir,\n \"agent-fabric\",\n `${pid !== undefined && /^\\d+$/.test(pid) ? pid : String(parentPid)}.env`,\n );\n}\n\n// The names `scripts/sp` takes from the file; nothing else is written.\nconst NAMES: ReadonlySet<string> = new Set(Object.values(SP_VARS));\n\n/**\n * The variables `scripts/sp` reads, kept as a plain object (the one the\n * shared pieces set and clear) and written to the file after each change.\n */\nexport class SpEnvFile {\n /** What the shared pieces set and clear; `write()` puts it in the file. */\n readonly vars: Record<string, string | undefined> = {};\n\n constructor(readonly path: string) {}\n\n /**\n * The file, whole, through a rename, so `scripts/sp` reads one state or\n * the next. A value with a line break could not be read back, so it is\n * left out. Throws what the file system throws.\n */\n write(): void {\n let text = \"\";\n for (const [name, value] of Object.entries(this.vars)) {\n if (!NAMES.has(name) || value === undefined || /[\\r\\n]/.test(value)) continue;\n text += `${name}=${value}\\n`;\n }\n mkdirSync(dirname(this.path), { recursive: true, mode: 0o700 });\n const staging = `${this.path}.${process.pid}.tmp`;\n writeFileSync(staging, text, { mode: 0o600 });\n renameSync(staging, this.path);\n }\n\n /** Removes the file, when the server stops; `scripts/sp` then finds no configuration. */\n remove(): void {\n rmSync(this.path, { force: true });\n }\n}\n","// The fabric add-on for the Claude Code channel plugin: the factory the\n// plugin's MCP server calls once at start, and the extension it returns\n// (`docs/plugins.md` §2.3, §2.4, §3.1, §3.4).\n//\n// What it does, in one screen. The fabric package's `fabricTracing()` gives\n// the three hooks the SDK takes; the plugin puts the request interceptor and\n// the heartbeat extras on its `AgentService` and the prompt interceptor on\n// the `Agents` client its agent tools prompt through. That alone makes the\n// session what an SDK-built agent is on the wire: the envelope's pair\n// adopted or a root minted per served prompt, an `edge` record before every\n// prompt Claude Code's model sends, the record counts on the heartbeat.\n//\n// The harness piece is the join of Claude Code's own model calls. Claude\n// Code sends `X-Claude-Code-Session-ID` on every model request and the\n// proxy files the calls under the session id; the plugin, an MCP server\n// inside the session, cannot touch those headers. So per served prompt the\n// add-on publishes the binding as the signed `served` pair on the edge\n// subject: `start` stamped with the arrival, naming the served thread and\n// the session the prompt was delivered to, and `end` with the outcome.\n//\n// The turn does not end with the reply. After `reply` completes the\n// request with `done`, Claude Code makes at least one more model call to\n// write its closing text. So an `ok` turn stays pending until the plugin's\n// `Stop` hook reports the turn's end (`turnStopped`) at a time after the\n// reply, and `end` carries that time; with no `Stop` within the bound\n// (`stopWaitMs`, 120 s by default) it carries the reply's. A failed or\n// expired request ends at once. So does a request the plugin answered\n// with the turn's final text (reason `final_text`): the model wrote no\n// reply, and the plugin sends that text at the turn's `Stop`, which has\n// already come. The plugin's reason for an end the model did not make\n// itself goes on `end` as the record's `reason`; the add-on's own end of\n// an open request at `stopping` carries `shutdown`.\n//\n// The served request's scope is kept by the plugin's request id from\n// `promptAccepted` to `promptEnded` and bound around every agent-tool\n// call. The plugin already re-enters the handler's async context (a\n// snapshot taken after the interceptors ran) before `aroundToolCall`, so\n// the binding is a no-op rebind the add-on makes anyway. The `409` loop\n// guard is the fabric package's two interceptors, after tracing's, and its\n// `aroundToolCall` inside the add-on's, which lifts the mark once the\n// request's calls have settled.\n//\n// ScratchPad (§9.13): when a volume is configured, the add-on keeps the\n// variables the package's skill (`skills/scratchpad`, loaded with the\n// package as a Claude Code plugin) reads through `scripts/sp` in a file the\n// package's SessionStart hook names to the Bash tool: the connection, the\n// workspace and the volume at start, the served prompt's trace and caller\n// from its arrival to its end (`scratchpad.ts`). It registers Claude Code as\n// reading references, hands the references Claude Code's model puts into\n// `prompt_agent` to the fabric package's ScratchPad extension, and answers\n// grant requests for what Claude Code published, by an SDK-built agent's\n// rule.\n\nimport {\n activeTrace,\n bindActiveTrace,\n fabricTracing,\n loopGuard,\n resolveEdgeSubject,\n servedPublisher,\n type AgentExtension,\n type AgentExtensionContext,\n type EndReason,\n type Outcome,\n type ServedPublisher,\n type ServedRequest,\n type ServedTurn,\n type TraceScope,\n READS_REFERENCES_KEY,\n} from \"@synadia-ai/agent-fabric\";\nimport { NatsAgentError } from \"@synadia-ai/agents\";\nimport {\n exportScratchPad,\n resolveScratchPad,\n ScratchPadHandOn,\n ServedPromptEnv,\n SP_VARS,\n SpEnvFile,\n spEnvFilePath,\n spPort,\n type ScratchPadSettings,\n} from \"./scratchpad.js\";\n\n/** The extension's name, as the plugin's status output lists it. */\nexport const EXTENSION_NAME = \"agent-fabric\";\n\n/** The name the proxy files Claude Code's calls under, and the served records carry. */\nexport const SERVED_HARNESS = \"claude\";\n\n/** How long an answered turn waits for the `Stop` hook before `end` carries the reply's time. */\nexport const DEFAULT_STOP_WAIT_MS = 120_000;\n\n/** The warning logged once at start when the plugin's identity is off. */\nexport const IDENTITY_OFF_WARNING =\n `${EXTENSION_NAME}: senderIdentity is off; trace records are signed, so none will be ` +\n \"published and each counts as dropped on the heartbeat. Set senderIdentity to signed.\";\n\n/** The line logged for a prompt that arrives while no session is known. */\nexport const NO_SESSION_LINE =\n `${EXTENSION_NAME}: no Claude Code session id known for this prompt, so no served pair; ` +\n \"its model calls stand as a harness thread of their own. Are the plugin's hooks registered?\";\n\n// Claude Code's session ids are UUIDs; the rule is the one the pre-split\n// plugin checked before it published a pair (`isClaudeSessionId`,\n// `agents/claude-code/src/session-id.ts` at `fbd16ab`): header-safe, so\n// nothing a header value could never hold reaches the record.\nconst SESSION_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;\n\n/** `true` iff `value` is shaped like a session id Claude Code would send. */\nexport function isClaudeSessionId(value: unknown): value is string {\n return typeof value === \"string\" && SESSION_ID_RE.test(value);\n}\n\n/** One served prompt, from `promptAccepted` to `promptEnded`. */\ninterface Served {\n readonly request: ServedRequest;\n /** The scope tracing bound around the prompt's handler. */\n readonly scope: TraceScope;\n /** The session the pair names; absent when none was known. */\n readonly sessionId: string | undefined;\n /** The pair; absent when the add-on publishes no records or knew no session. */\n readonly turn: ServedTurn | undefined;\n}\n\n/** An answered prompt whose turn waits for the `Stop` hook. */\ninterface AwaitingStop {\n readonly sessionId: string;\n readonly turn: ServedTurn;\n /** When `reply` completed the request: `promptEnded`'s time. */\n readonly repliedAtMs: number;\n readonly timer: ReturnType<typeof setTimeout>;\n}\n\nfunction stopWaitFrom(options: Readonly<Record<string, unknown>>): number {\n const value = options[\"stopWaitMs\"];\n if (value === undefined) return DEFAULT_STOP_WAIT_MS;\n if (typeof value !== \"number\" || !Number.isFinite(value) || value < 0) {\n throw new NatsAgentError(`${EXTENSION_NAME}: options.stopWaitMs must be a number of ms ≥ 0`);\n }\n return value;\n}\n\n/**\n * The factory: the module's default export. Called once by the plugin's\n * MCP server, before it connects, with what it knows then. Resolves\n * ScratchPad's settings (which may read the plugin's NATS context) and\n * builds the extension with them. Throws `NatsAgentError` for an edge\n * subject that can never be published to, or a `stopWaitMs` option that\n * is not a duration.\n *\n * `env` is where the variables are read from; a test passes its own.\n */\nexport async function fabricExtension(\n ctx: AgentExtensionContext,\n env: NodeJS.ProcessEnv = process.env,\n): Promise<AgentExtension> {\n return createFabricExtension(ctx, env, await resolveScratchPad(ctx, env));\n}\n\n/**\n * The extension, built synchronously from settings already resolved:\n * without `scratchPad`, tracing, the `served` pair and the guard alone.\n */\nexport function createFabricExtension(\n ctx: AgentExtensionContext,\n env: NodeJS.ProcessEnv = process.env,\n scratchPad?: ScratchPadSettings,\n): AgentExtension {\n const edgeSubject = resolveEdgeSubject(ctx.options, env);\n const stopWaitMs = stopWaitFrom(ctx.options);\n const tracing = fabricTracing({ edgeSubject });\n const guard = loopGuard();\n const log = ctx.logger;\n\n // Made at `started`, from the plugin's client, which signs as the\n // plugin's identity. A prompt accepted before then gets no pair. With\n // the edge subject `null` (propagate-only) there is never one.\n let publisher: ServedPublisher | undefined;\n // The session Claude Code is in now, as the `SessionStart` hook last\n // reported it; the fallback when the plugin names none on a request.\n let currentSession: string | undefined;\n const served = new Map<string, Served>();\n // Answered turns in the order they were answered.\n const awaitingStop: AwaitingStop[] = [];\n\n const release = (waiting: AwaitingStop): void => {\n const at = awaitingStop.indexOf(waiting);\n if (at >= 0) awaitingStop.splice(at, 1);\n clearTimeout(waiting.timer);\n };\n\n let warnedIdentityOff = false;\n\n // ScratchPad's variables, in the file the package's hook names to the\n // Bash tool. Without the plugin's state directory there is no file to\n // name, and the skill's scripts/sp finds no configuration.\n let spEnv: SpEnvFile | undefined;\n if (scratchPad !== undefined) {\n if (ctx.settings.stateDir !== undefined) {\n spEnv = new SpEnvFile(spEnvFilePath(ctx.settings.stateDir, env));\n } else {\n log.warn(\n `${EXTENSION_NAME}: the plugin names no state directory, so the skill's ` +\n \"scripts/sp gets no ScratchPad settings\",\n );\n }\n }\n const writeSpEnv = (): void => {\n if (spEnv === undefined) return;\n try {\n spEnv.write();\n } catch (err) {\n log.warn(`${EXTENSION_NAME}: ScratchPad's settings for scripts/sp: ${String(err)}`);\n }\n };\n if (scratchPad !== undefined && spEnv !== undefined) {\n exportScratchPad(scratchPad, spEnv.vars);\n writeSpEnv();\n }\n const promptEnv = spEnv !== undefined ? new ServedPromptEnv(spEnv.vars) : undefined;\n const handOn = scratchPad !== undefined ? new ScratchPadHandOn() : undefined;\n\n return {\n name: EXTENSION_NAME,\n // The service: tracing first, so the guard runs inside the scope tracing\n // bound and a malformed pair is refused with 400 before the guard\n // looks; the plugin appends its own (the tools' scope) after these.\n // The ScratchPad extension's, last, remembers the references each\n // served prompt brings, which Claude Code may hand on.\n requestInterceptors: [\n tracing.requestInterceptor,\n guard.requestInterceptor,\n ...(handOn !== undefined ? [handOn.requestInterceptor] : []),\n ],\n // The client Claude Code's agent tools prompt through: the edge and the\n // pair, then the waiting mark. Both read the ambient scope, so the\n // order between them does not matter.\n promptInterceptors: [tracing.promptInterceptor, guard.promptInterceptor],\n heartbeatExtras: tracing.heartbeatExtras,\n ...(handOn !== undefined\n ? {\n // References in Claude Code's `prompt_agent`: granted to a\n // receiver that reads them, removed with a note for any other.\n toolExtensions: [handOn],\n // So a caller's `prompt_agent` hands references to Claude Code.\n metadata: { [READS_REFERENCES_KEY]: \"true\" },\n }\n : {}),\n\n started({ agents, service }) {\n if (ctx.settings.senderIdentity !== \"signed\" && !warnedIdentityOff) {\n warnedIdentityOff = true;\n log.warn(IDENTITY_OFF_WARNING);\n }\n if (edgeSubject !== null) {\n publisher = servedPublisher({ agents, subject: edgeSubject, logger: log });\n }\n log.info(\n `${EXTENSION_NAME}: tracing ${service.subject.prompt}` +\n (edgeSubject === null\n ? \" (propagate-only: lineage forwarded, no edge or served record published)\"\n : `, edge and served records on ${edgeSubject}`),\n );\n if (scratchPad !== undefined && handOn !== undefined) {\n if (spEnv !== undefined) {\n spEnv.vars[SP_VARS.creator] = service.subject.prompt;\n writeSpEnv();\n }\n const port = spPort(scratchPad, service.subject.prompt, env);\n if (port !== undefined) handOn.start({ scratchPad: port, agents, service, logger: log });\n else\n log.warn(\n `${EXTENSION_NAME}: no sp for this platform (set SCRATCHPAD_BIN); ` +\n \"references in prompt_agent are not handed on, and grant requests not answered\",\n );\n log.info(\n `${EXTENSION_NAME}: ScratchPad volume ${scratchPad.volume}` +\n (scratchPad.dir !== undefined ? `, workspace ${scratchPad.dir}` : \", no workspace\") +\n (spEnv !== undefined ? `, for the skill's scripts/sp through ${spEnv.path}` : \"\"),\n );\n }\n },\n\n async stopping() {\n // The plugin calls this before it fails the requests still open, and\n // no `Stop` will come any more: every turn ends here, an answered one\n // at its reply, an open one now.\n for (const waiting of [...awaitingStop]) {\n release(waiting);\n waiting.turn.settle(\"ok\", waiting.repliedAtMs);\n }\n for (const [id, entry] of served) {\n served.delete(id);\n entry.turn?.settle(\"error\", undefined, \"shutdown\");\n }\n // No served prompt any more, and no server to serve one.\n spEnv?.remove();\n await publisher?.flush();\n },\n\n events: {\n sessionStarted(sessionId) {\n if (isClaudeSessionId(sessionId)) currentSession = sessionId;\n },\n\n promptAccepted(request) {\n // In the handler's async context, inside the scope tracing bound.\n const scope = activeTrace();\n // From here to its end this prompt is the one Claude Code works on,\n // and the one `scripts/sp` works for.\n if (promptEnv !== undefined) {\n promptEnv.enter(request, scope);\n writeSpEnv();\n }\n if (scope === undefined) return;\n const named = request.sessionId ?? currentSession;\n const sessionId = isClaudeSessionId(named) ? named : undefined;\n let turn: ServedTurn | undefined;\n if (sessionId === undefined) {\n log.warn(NO_SESSION_LINE);\n } else {\n // `beginTurn` stamps the arrival now; `bind` publishes `start`.\n // The session is bound at arrival, so a `/clear` during the turn\n // does not move the binding.\n turn = publisher?.beginTurn(scope, SERVED_HARNESS);\n turn?.bind(sessionId);\n }\n served.set(request.id, { request, scope, sessionId, turn });\n },\n\n promptEnded(request, outcome: Outcome, atMs, reason?: EndReason) {\n const entry = served.get(request.id);\n served.delete(request.id);\n if (promptEnv !== undefined) {\n // Claude Code may hold a second prompt in the same turn: the\n // variables go back to the latest one still open.\n promptEnv.leave(request);\n const open = [...served.values()].at(-1);\n if (open !== undefined) promptEnv.enter(open.request, open.scope);\n writeSpEnv();\n }\n if (entry === undefined) return;\n const { turn, sessionId } = entry;\n if (turn === undefined || sessionId === undefined) return;\n // A failure ends at once, and so does an answer the plugin sent from\n // the turn's final text: it comes at the turn's `Stop`, so the turn\n // is already over.\n if (outcome !== \"ok\" || reason === \"final_text\") {\n turn.settle(outcome, atMs, reason);\n return;\n }\n // Answered, but Claude Code is still writing its closing text.\n const waiting: AwaitingStop = {\n sessionId,\n turn,\n repliedAtMs: atMs,\n timer: setTimeout(() => {\n release(waiting);\n turn.settle(\"ok\", atMs);\n }, stopWaitMs),\n };\n waiting.timer.unref?.();\n awaitingStop.push(waiting);\n },\n\n turnStopped(sessionId, atMs) {\n // One `Stop` ends one turn of Claude Code's, and every prompt\n // answered in it before the stop: the oldest first, so two\n // prompts answered in one turn share its end, and a prompt\n // answered after this stop waits for the next.\n for (const waiting of [...awaitingStop]) {\n if (sessionId !== undefined && waiting.sessionId !== sessionId) continue;\n if (waiting.repliedAtMs >= atMs) continue;\n release(waiting);\n waiting.turn.settle(\"ok\", atMs);\n }\n },\n\n aroundToolCall(request: ServedRequest | undefined, _toolName, run) {\n const scope = request === undefined ? undefined : served.get(request.id)?.scope;\n return scope === undefined\n ? run()\n : bindActiveTrace(scope, () => guard.aroundToolCall(scope, run));\n },\n },\n };\n}\n"]}
@@ -0,0 +1,15 @@
1
+ {
2
+ "hooks": {
3
+ "SessionStart": [
4
+ {
5
+ "hooks": [
6
+ {
7
+ "type": "command",
8
+ "command": "sh \"${CLAUDE_PLUGIN_ROOT}/hooks/session-start.sh\"",
9
+ "timeout": 10
10
+ }
11
+ ]
12
+ }
13
+ ]
14
+ }
15
+ }
@@ -0,0 +1,28 @@
1
+ #!/bin/sh
2
+ # The add-on's one Claude Code hook, at SessionStart: names to the Bash tool
3
+ # the file the add-on's module keeps ScratchPad's variables in, as
4
+ # SP_ENV_FILE, which the skill's scripts/sp reads on every call
5
+ # (`docs/plugins.md` §9.13).
6
+ #
7
+ # The module runs in the NATS channel plugin's MCP server, a sibling of the
8
+ # Bash tool's processes, so it cannot set their environment; it writes the
9
+ # variables to `<state dir>/agent-fabric/<CLAUDE_PID>.env` instead: the
10
+ # connection, the workspace and the volume at start, the served prompt's
11
+ # trace and caller from its arrival to its end. The state directory is the
12
+ # plugin's rule, NATS_STATE_DIR or ~/.claude/channels/nats; CLAUDE_PID is the
13
+ # Claude Code process, which Claude Code hands its hooks and its MCP servers
14
+ # alike. Claude Code keeps what this appends to CLAUDE_ENV_FILE for every
15
+ # later Bash command of the session.
16
+ #
17
+ # Prints nothing and exits 0 whatever happens: a hook must never interrupt a
18
+ # session.
19
+ [ -n "${CLAUDE_ENV_FILE:-}" ] || exit 0
20
+ case ${CLAUDE_PID:-} in
21
+ '' | *[!0-9]*) exit 0 ;;
22
+ esac
23
+ state=${NATS_STATE_DIR:-${HOME:-}/.claude/channels/nats}
24
+ file=$state/agent-fabric/$CLAUDE_PID.env
25
+ # Single-quoted for the shell that reads CLAUDE_ENV_FILE.
26
+ quoted=$(printf '%s' "$file" | sed "s/'/'\\\\''/g")
27
+ printf "export SP_ENV_FILE='%s'\n" "$quoted" >>"$CLAUDE_ENV_FILE" 2>/dev/null
28
+ exit 0
package/package.json CHANGED
@@ -1,6 +1,89 @@
1
1
  {
2
2
  "name": "@synadia-ai/agent-fabric-claude-code",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "The Synadia Agent Fabric add-on for the Claude Code channel plugin: the fabric's tracing on the plugin's service and client, each served prompt bound to its Claude Code session by the signed served pair (end at the turn's Stop), and the loop guard, as one extension module the plugin loads.",
5
+ "type": "module",
6
+ "main": "./dist/index.cjs",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js",
13
+ "require": "./dist/index.cjs",
14
+ "default": "./dist/index.js"
15
+ },
16
+ "./package.json": "./package.json"
17
+ },
18
+ "files": [
19
+ "dist",
20
+ ".claude-plugin",
21
+ "hooks",
22
+ "skills",
23
+ "README.md",
24
+ "CHANGELOG.md",
25
+ "LICENSE"
26
+ ],
27
+ "sideEffects": false,
28
+ "engines": {
29
+ "node": ">=20.0.0"
30
+ },
31
+ "scripts": {
32
+ "build": "tsup",
33
+ "build:sp": "sh ../scratchpad-skill/install.sh --dest skills/scratchpad --allowed-tools 'Bash(${CLAUDE_SKILL_DIR}/scripts/sp *)'",
34
+ "typecheck": "tsc --noEmit",
35
+ "lint": "eslint .",
36
+ "lint:fix": "eslint . --fix",
37
+ "format": "prettier --write .",
38
+ "format:check": "prettier --check .",
39
+ "test": "vitest run",
40
+ "test:unit": "vitest run test/unit",
41
+ "test:integration": "vitest run test/integration",
42
+ "test:watch": "vitest",
43
+ "check": "npm run typecheck && npm run lint && npm run format:check && npm run test",
44
+ "prepack": "npm run build:sp",
45
+ "prepublishOnly": "npm run build"
46
+ },
47
+ "keywords": [
48
+ "nats",
49
+ "ai",
50
+ "agents",
51
+ "agent-fabric",
52
+ "tracing",
53
+ "claude-code",
54
+ "synadia",
55
+ "sdk"
56
+ ],
57
+ "license": "Apache-2.0",
58
+ "author": "Synadia Communications",
59
+ "repository": {
60
+ "type": "git",
61
+ "url": "git+https://github.com/synadia-ai/agent-fabric-sdk.git",
62
+ "directory": "plugins/claude-code"
63
+ },
64
+ "homepage": "https://github.com/synadia-ai/agent-fabric-sdk/tree/main/plugins/claude-code",
65
+ "bugs": {
66
+ "url": "https://github.com/synadia-ai/agent-fabric-sdk/issues"
67
+ },
68
+ "publishConfig": {
69
+ "access": "public"
70
+ },
71
+ "dependencies": {
72
+ "@synadia-ai/agent-fabric": "^0.1.0",
73
+ "@synadia-ai/agent-service": "^0.6.0",
74
+ "@synadia-ai/agents": "^0.6.0"
75
+ },
76
+ "devDependencies": {
77
+ "@nats-io/nats-core": "^3.4.0",
78
+ "@nats-io/transport-node": "^3.4.0",
79
+ "@types/node": "^20.16.0",
80
+ "ajv": "^8.17.0",
81
+ "eslint": "^9.0.0",
82
+ "eslint-config-prettier": "^9.1.0",
83
+ "prettier": "3.9.5",
84
+ "tsup": "^8.3.0",
85
+ "typescript": "~5.6.0",
86
+ "typescript-eslint": "^8.10.0",
87
+ "vitest": "^3.2.0"
88
+ }
89
+ }
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Support. While redistributing the Work or
166
+ Derivative Works thereof, You may choose to offer, and charge a fee
167
+ for, acceptance of support, warranty, indemnity, or other liability
168
+ obligations and/or rights consistent with this License. However, in
169
+ accepting such obligations, You may act only on Your own behalf and
170
+ on Your sole responsibility, not on behalf of any other Contributor,
171
+ and only if You agree to indemnify, defend, and hold each Contributor
172
+ harmless for any liability incurred by, or claims asserted against,
173
+ such Contributor by reason of your accepting any such warranty or
174
+ additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Synadia Communications
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
200
+ implied. See the License for the specific language governing permissions
201
+ and limitations under the License.