@synadia-ai/agent-fabric-claude-code 0.1.0 → 0.2.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/.claude-plugin/plugin.json +4 -4
- package/.mcp.json +14 -0
- package/BUILD +4 -0
- package/LICENSE +18 -17
- package/README.md +52 -441
- package/hooks/hooks.json +31 -0
- package/hooks/session-event.js +11 -0
- package/package.json +23 -72
- package/runtime/chunk-prncr0vg.js +38 -0
- package/runtime/fabric.js +7 -0
- package/runtime/server.js +63 -0
- package/skills/configure/SKILL.md +190 -0
- package/skills/configure/list-contexts.sh +22 -0
- package/CHANGELOG.md +0 -18
- package/dist/index.cjs +0 -277
- package/dist/index.cjs.map +0 -1
- package/dist/index.d.cts +0 -63
- package/dist/index.d.ts +0 -63
- package/dist/index.js +0 -248
- package/dist/index.js.map +0 -1
package/dist/index.d.ts
DELETED
|
@@ -1,63 +0,0 @@
|
|
|
1
|
-
import { AgentExtensionContext, ScratchPadSettings, AgentExtension } from '@synadia-ai/agent-fabric';
|
|
2
|
-
export { SCRATCHPAD_OPTION, SP_VARS, ScratchPadHandOn } from '@synadia-ai/agent-fabric';
|
|
3
|
-
|
|
4
|
-
/** The variable that names the file to `scripts/sp`, set by the package's hook. */
|
|
5
|
-
declare const SP_ENV_FILE_VAR = "SP_ENV_FILE";
|
|
6
|
-
/** The sp binary this package ships for this machine, or `SCRATCHPAD_BIN`. */
|
|
7
|
-
declare function spBinary(env: Record<string, string | undefined>): string | undefined;
|
|
8
|
-
/**
|
|
9
|
-
* The file for the Claude Code process this server runs under:
|
|
10
|
-
* `<stateDir>/agent-fabric/<pid>.env`, where the hook looks for it. The pid
|
|
11
|
-
* is `CLAUDE_PID`, which Claude Code hands its hooks and its MCP servers
|
|
12
|
-
* alike, else the parent's, as the plugin keys its own files.
|
|
13
|
-
*/
|
|
14
|
-
declare function spEnvFilePath(stateDir: string, env: Record<string, string | undefined>, parentPid?: number): string;
|
|
15
|
-
/**
|
|
16
|
-
* The variables `scripts/sp` reads, kept as a plain object (the one the
|
|
17
|
-
* shared pieces set and clear) and written to the file after each change.
|
|
18
|
-
*/
|
|
19
|
-
declare class SpEnvFile {
|
|
20
|
-
readonly path: string;
|
|
21
|
-
/** What the shared pieces set and clear; `write()` puts it in the file. */
|
|
22
|
-
readonly vars: Record<string, string | undefined>;
|
|
23
|
-
constructor(path: string);
|
|
24
|
-
/**
|
|
25
|
-
* The file, whole, through a rename, so `scripts/sp` reads one state or
|
|
26
|
-
* the next. A value with a line break could not be read back, so it is
|
|
27
|
-
* left out. Throws what the file system throws.
|
|
28
|
-
*/
|
|
29
|
-
write(): void;
|
|
30
|
-
/** Removes the file, when the server stops; `scripts/sp` then finds no configuration. */
|
|
31
|
-
remove(): void;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
/** The extension's name, as the plugin's status output lists it. */
|
|
35
|
-
declare const EXTENSION_NAME = "agent-fabric";
|
|
36
|
-
/** The name the proxy files Claude Code's calls under, and the served records carry. */
|
|
37
|
-
declare const SERVED_HARNESS = "claude";
|
|
38
|
-
/** How long an answered turn waits for the `Stop` hook before `end` carries the reply's time. */
|
|
39
|
-
declare const DEFAULT_STOP_WAIT_MS = 120000;
|
|
40
|
-
/** The warning logged once at start when the plugin's identity is off. */
|
|
41
|
-
declare const IDENTITY_OFF_WARNING: string;
|
|
42
|
-
/** The line logged for a prompt that arrives while no session is known. */
|
|
43
|
-
declare const NO_SESSION_LINE: string;
|
|
44
|
-
/** `true` iff `value` is shaped like a session id Claude Code would send. */
|
|
45
|
-
declare function isClaudeSessionId(value: unknown): value is string;
|
|
46
|
-
/**
|
|
47
|
-
* The factory: the module's default export. Called once by the plugin's
|
|
48
|
-
* MCP server, before it connects, with what it knows then. Resolves
|
|
49
|
-
* ScratchPad's settings (which may read the plugin's NATS context) and
|
|
50
|
-
* builds the extension with them. Throws `NatsAgentError` for an edge
|
|
51
|
-
* subject that can never be published to, or a `stopWaitMs` option that
|
|
52
|
-
* is not a duration.
|
|
53
|
-
*
|
|
54
|
-
* `env` is where the variables are read from; a test passes its own.
|
|
55
|
-
*/
|
|
56
|
-
declare function fabricExtension(ctx: AgentExtensionContext, env?: NodeJS.ProcessEnv): Promise<AgentExtension>;
|
|
57
|
-
/**
|
|
58
|
-
* The extension, built synchronously from settings already resolved:
|
|
59
|
-
* without `scratchPad`, tracing, the `served` pair and the guard alone.
|
|
60
|
-
*/
|
|
61
|
-
declare function createFabricExtension(ctx: AgentExtensionContext, env?: NodeJS.ProcessEnv, scratchPad?: ScratchPadSettings): AgentExtension;
|
|
62
|
-
|
|
63
|
-
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 };
|
package/dist/index.js
DELETED
|
@@ -1,248 +0,0 @@
|
|
|
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
|
package/dist/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
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,EAAc;AAAd,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAAA,EAAe;AAAA,EAAf,IAAA;AAAA;AAAA,EAFZ,OAA2C,EAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASrD,KAAA,GAAc;AACZ,IAAA,IAAI,IAAA,GAAO,EAAA;AACX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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"]}
|