@pairdraw/harness 0.0.0-stage → 0.16.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Danila Poyarkov and OpenPencil contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,18 @@
1
- # Temporary Holding Version
1
+ # @pairdraw/harness
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Optional Node companion runtime for coding-agent harness sessions. It owns the backend-neutral session lifecycle, opaque resume-state persistence, and the JSONL sidecar protocol used by host applications.
4
+
5
+ The first backend uses AI SDK `HarnessAgent`, Pi, and local `just-bash`. Pi runs in the Node host process; `just-bash` provides an isolated in-memory workspace and shell without requiring cloud infrastructure.
6
+
7
+ ## Current scope
8
+
9
+ - Backend-neutral, streaming session service.
10
+ - Atomic, bounded persistence of opaque harness resume state.
11
+ - JSONL stdio sidecar transport.
12
+ - Pi + `just-bash` backend.
13
+
14
+ The package is installed as an optional companion CLI for the desktop application. It is not bundled into every Tauri build; install `@pairdraw/harness` globally to make the `pairdraw-harness` command available. It runs on Node 22.15 or later, or Bun: Pi's MCP adapter publishes TypeScript sources, which the companion strips through Node's module hooks. Credentials are supplied to the companion process at runtime and are never written to resume-state storage.
15
+
16
+ ## Local sandbox limitation
17
+
18
+ `just-bash` is process-local and in-memory. Multi-turn sessions work while the sidecar remains alive, but its sandbox cannot be reattached after a process restart. A backend that reports `sessionResume: 'live-process'`, as Pi does, therefore starts a stopped session fresh and drops its saved state. Durable restart recovery requires a persistent sandbox provider in a later integration.
@@ -0,0 +1,249 @@
1
+ import "./rolldown-runtime-ClRpJifh.mjs";
2
+ import { PiAuthenticationMode, PiHarnessSettings } from "@ai-sdk/harness-pi";
3
+ //#region src/protocol.d.ts
4
+ type JSONPrimitive = null | boolean | number | string;
5
+ type JSONValue = JSONPrimitive | JSONValue[] | {
6
+ [key: string]: JSONValue;
7
+ };
8
+ declare const HARNESS_ADAPTER_IDS: readonly ["pi"];
9
+ declare const HARNESS_SANDBOX_IDS: readonly ["just-bash"];
10
+ type HarnessAdapterID = (typeof HARNESS_ADAPTER_IDS)[number];
11
+ type HarnessSandboxID = (typeof HARNESS_SANDBOX_IDS)[number];
12
+ interface HarnessSessionConfiguration {
13
+ adapter: HarnessAdapterID;
14
+ sandbox: HarnessSandboxID;
15
+ model: string;
16
+ settings?: Record<string, JSONValue>;
17
+ mcpServers?: Record<string, Record<string, JSONValue>>;
18
+ instructions?: string;
19
+ skills?: HarnessSkill[];
20
+ }
21
+ /** A skill the agent may load: its SKILL.md body and the text files beside it. */
22
+ interface HarnessSkill {
23
+ name: string;
24
+ description: string;
25
+ content: string;
26
+ files?: {
27
+ path: string;
28
+ content: string;
29
+ }[];
30
+ }
31
+ interface HarnessProviderCapability {
32
+ adapter: HarnessAdapterID;
33
+ sandboxes: readonly HarnessSandboxID[];
34
+ structuredOutput: boolean;
35
+ sessionResume: 'live-process' | 'persistent';
36
+ turnContinuation: boolean;
37
+ }
38
+ interface HarnessTurnInput {
39
+ sessionId: string;
40
+ prompt: string;
41
+ }
42
+ type HarnessRequest = {
43
+ id: string;
44
+ method: 'service.capabilities';
45
+ params?: Record<string, never>;
46
+ } | {
47
+ id: string;
48
+ method: 'session.create';
49
+ params: {
50
+ sessionId: string;
51
+ configuration: HarnessSessionConfiguration;
52
+ };
53
+ } | {
54
+ id: string;
55
+ method: 'session.turn';
56
+ params: HarnessTurnInput;
57
+ } | {
58
+ id: string;
59
+ method: 'session.cancel';
60
+ params: {
61
+ sessionId: string;
62
+ };
63
+ } | {
64
+ id: string;
65
+ method: 'session.stop';
66
+ params: {
67
+ sessionId: string;
68
+ };
69
+ } | {
70
+ id: string;
71
+ method: 'session.destroy';
72
+ params: {
73
+ sessionId: string;
74
+ };
75
+ } | {
76
+ id: string;
77
+ method: 'service.shutdown';
78
+ params?: Record<string, never>;
79
+ };
80
+ /** A turn's tokens; input counts cached tokens too, which the cache fields break out. */
81
+ interface HarnessTurnUsage {
82
+ inputTokens: number | null;
83
+ outputTokens: number | null;
84
+ cacheReadTokens: number | null;
85
+ cacheWriteTokens: number | null;
86
+ }
87
+ type HarnessTurnEvent = {
88
+ type: 'text-delta';
89
+ text: string;
90
+ } | {
91
+ type: 'reasoning-delta';
92
+ text: string;
93
+ } | {
94
+ type: 'tool-call';
95
+ toolCallId: string;
96
+ toolName: string;
97
+ input: JSONValue;
98
+ } | {
99
+ type: 'tool-result';
100
+ toolCallId: string;
101
+ toolName: string;
102
+ output: JSONValue;
103
+ } | {
104
+ type: 'finish';
105
+ finishReason: string;
106
+ usage?: HarnessTurnUsage;
107
+ } | {
108
+ type: 'error';
109
+ message: string;
110
+ };
111
+ type HarnessSidecarMessage = {
112
+ type: 'response';
113
+ id: string;
114
+ result?: JSONValue;
115
+ error?: string;
116
+ } | {
117
+ type: 'turn.event';
118
+ id: string;
119
+ event: HarnessTurnEvent;
120
+ };
121
+ declare const MAX_PROTOCOL_LINE_BYTES: number;
122
+ declare const MAX_PROMPT_LENGTH: number;
123
+ declare function parseHarnessRequest(line: string): HarnessRequest;
124
+ //#endregion
125
+ //#region src/backends/types.d.ts
126
+ type HarnessResumeState = {
127
+ type: 'resume-session';
128
+ harnessId: string;
129
+ specificationVersion: 'harness-v1';
130
+ data: JSONValue;
131
+ continueFrom?: JSONValue;
132
+ };
133
+ interface BackendSession {
134
+ readonly sessionId: string;
135
+ readonly isResume: boolean;
136
+ runTurn(prompt: string, signal?: AbortSignal): AsyncIterable<BackendEvent>;
137
+ stop(): Promise<HarnessResumeState>;
138
+ destroy(): Promise<void>;
139
+ }
140
+ type BackendEvent = {
141
+ type: 'text-delta';
142
+ text: string;
143
+ } | {
144
+ type: 'reasoning-delta';
145
+ text: string;
146
+ } | {
147
+ type: 'tool-call';
148
+ toolCallId: string;
149
+ toolName: string;
150
+ input: JSONValue;
151
+ } | {
152
+ type: 'tool-result';
153
+ toolCallId: string;
154
+ toolName: string;
155
+ output: JSONValue;
156
+ } | {
157
+ type: 'finish';
158
+ finishReason: string;
159
+ usage?: HarnessTurnUsage;
160
+ } | {
161
+ type: 'error';
162
+ message: string;
163
+ };
164
+ interface HarnessBackend {
165
+ readonly id: HarnessAdapterID;
166
+ readonly capabilities: HarnessProviderCapability;
167
+ createSession(options: {
168
+ sessionId: string;
169
+ resumeState?: HarnessResumeState;
170
+ configuration?: HarnessSessionConfiguration;
171
+ signal?: AbortSignal;
172
+ }): Promise<BackendSession>;
173
+ }
174
+ //#endregion
175
+ //#region src/backends/pi.d.ts
176
+ type PiThinkingLevel = NonNullable<PiHarnessSettings['thinkingLevel']>;
177
+ interface PiHarnessBackendOptions {
178
+ auth?: PiAuthenticationMode;
179
+ apiKey?: string;
180
+ model?: string;
181
+ thinkingLevel?: PiThinkingLevel;
182
+ agentDir?: string;
183
+ mcpServers?: Record<string, unknown>;
184
+ instructions?: string;
185
+ permissionMode?: 'allow-all' | 'allow-reads' | 'allow-edits';
186
+ }
187
+ declare class PiHarnessBackend implements HarnessBackend {
188
+ private readonly defaults;
189
+ readonly id = "pi";
190
+ readonly capabilities: {
191
+ readonly adapter: "pi";
192
+ readonly sandboxes: readonly ["just-bash"];
193
+ readonly structuredOutput: false;
194
+ readonly sessionResume: "live-process";
195
+ readonly turnContinuation: true;
196
+ };
197
+ constructor(defaults?: PiHarnessBackendOptions);
198
+ createSession(options: {
199
+ sessionId: string;
200
+ resumeState?: HarnessResumeState;
201
+ configuration?: HarnessSessionConfiguration;
202
+ signal?: AbortSignal;
203
+ }): Promise<BackendSession>;
204
+ }
205
+ //#endregion
206
+ //#region src/session-store.d.ts
207
+ interface ResumeStateStore {
208
+ load(sessionId: string): Promise<HarnessResumeState | undefined>;
209
+ save(sessionId: string, state: HarnessResumeState): Promise<void>;
210
+ remove(sessionId: string): Promise<void>;
211
+ }
212
+ declare class FileResumeStateStore implements ResumeStateStore {
213
+ private readonly root;
214
+ constructor(root: string);
215
+ load(sessionId: string): Promise<HarnessResumeState | undefined>;
216
+ save(sessionId: string, state: HarnessResumeState): Promise<void>;
217
+ remove(sessionId: string): Promise<void>;
218
+ }
219
+ //#endregion
220
+ //#region src/service.d.ts
221
+ declare class HarnessSessionService {
222
+ private readonly backends;
223
+ private readonly store;
224
+ private readonly sessions;
225
+ private readonly turns;
226
+ /** Sessions whose last turn ended because it was cancelled. */
227
+ private readonly cancelled;
228
+ constructor(backends: ReadonlyMap<string, HarnessBackend>, store: ResumeStateStore);
229
+ capabilities(): JSONValue;
230
+ createSession(sessionId: string, configuration: HarnessSessionConfiguration, signal?: AbortSignal): Promise<{
231
+ isResume: boolean;
232
+ }>;
233
+ runTurn(sessionId: string, prompt: string, signal?: AbortSignal): AsyncIterable<BackendEvent>;
234
+ /** Whether the session's last turn ended because it was cancelled, not because it finished. */
235
+ lastTurnCancelled(sessionId: string): boolean;
236
+ cancelTurn(sessionId: string): void;
237
+ stopSession(sessionId: string): Promise<void>;
238
+ /**
239
+ * A backend that resumes only within its live process (Pi's in-memory just-bash sandbox)
240
+ * cannot use saved state, and passing it makes every later session with that ID fail.
241
+ */
242
+ private loadResumeState;
243
+ destroySession(sessionId: string): Promise<void>;
244
+ shutdown(): Promise<void>;
245
+ private requireSession;
246
+ }
247
+ //#endregion
248
+ export { type BackendEvent, type BackendSession, FileResumeStateStore, type HarnessAdapterID, type HarnessBackend, type HarnessProviderCapability, type HarnessRequest, type HarnessResumeState, type HarnessSandboxID, type HarnessSessionConfiguration, HarnessSessionService, type HarnessSidecarMessage, type HarnessSkill, type HarnessTurnEvent, type HarnessTurnUsage, type JSONValue, MAX_PROMPT_LENGTH, MAX_PROTOCOL_LINE_BYTES, PiHarnessBackend, type PiHarnessBackendOptions, type ResumeStateStore, parseHarnessRequest };
249
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/protocol.ts","../src/backends/types.ts","../src/backends/pi.ts","../src/session-store.ts","../src/service.ts"],"mappings":";;;KAAK;KACO,YAAY,gBAAgB;GAAiB,cAAc;;cAEjE;cACA;KAEM,2BAA2B;KAC3B,2BAA2B;UAEtB;EACf,SAAS;EACT,SAAS;EACT;EACA,WAAW,eAAe;EAC1B,aAAa,eAAe,eAAe;EAC3C;EACA,SAAS;;;UAIM;EACf;EACA;EACA;EACA;IAAU;IAAc;;;UAGT;EACf,SAAS;EACT,oBAAoB;EACpB;EACA;EACA;;UAGQ;EACR;EACA;;KAGU;EAEN;EACA;EACA,SAAS;;EAGT;EACA;EACA;IAAU;IAAmB,eAAe;;;EAE5C;EAAY;EAAwB,QAAQ;;EAC5C;EAAY;EAA0B;IAAU;;;EAChD;EAAY;EAAwB;IAAU;;;EAC9C;EAAY;EAA2B;IAAU;;;EACjD;EAAY;EAA4B,SAAS;;;UAGtC;EACf;EACA;EACA;EACA;;KAGU;EACN;EAAoB;;EACpB;EAAyB;;EACzB;EAAmB;EAAoB;EAAkB,OAAO;;EAChE;EAAqB;EAAoB;EAAkB,QAAQ;;EACnE;EAAgB;EAAsB,QAAQ;;EAC9C;EAAe;;KAET;EACN;EAAkB;EAAY,SAAS;EAAW;;EAClD;EAAoB;EAAY,OAAO;;cAEhC;cACA;iBAyFG,oBAAoB,eAAe;;;KC/JvC;EACV;EACA;EACA;EACA,MAAM;EACN,eAAe;;UAGA;WACN;WACA;EACT,QAAQ,gBAAgB,SAAS,cAAc,cAAc;EAC7D,QAAQ,QAAQ;EAChB,WAAW;;KAGD;EACN;EAAoB;;EACpB;EAAyB;;EACzB;EAAmB;EAAoB;EAAkB,OAAO;;EAChE;EAAqB;EAAoB;EAAkB,QAAQ;;EACnE;EAAgB;EAAsB,QAAQ;;EAC9C;EAAe;;UAEJ;WACN,IAAI;WACJ,cAAc;EACvB,cAAc;IACZ;IACA,cAAc;IACd,gBAAgB;IAChB,SAAS;MACP,QAAQ;;;;KC9BT,kBAAkB,YAAY;UAElB;EACf,OAAO;EACP;EACA;EACA,gBAAgB;EAChB;EACA,aAAa;EACb;EACA;;cAoFW,4BAA4B;mBAUV;WATpB;WACA;;;;;;;EAQoB,YAAA,WAAU;EAEjC,cAAc;IAClB;IACA,cAAc;IACd,gBAAgB;IAChB,SAAS;MACP,QAAQ;;;;UC/GG;EACf,KAAK,oBAAoB,QAAQ;EACjC,KAAK,mBAAmB,OAAO,qBAAqB;EACpD,OAAO,oBAAoB;;cAoBhB,gCAAgC;mBACd;EAAA,YAAA;EAEvB,KAAK,oBAAoB,QAAQ;EAuBjC,KAAK,mBAAmB,OAAO,qBAAqB;EAUpD,OAAO,oBAAoB;;;;cCjEtB;mBAOQ;mBACA;mBAPF;mBACA;;mBAEA;EAGE,YAAA,UAAU,oBAAoB,iBAC9B,OAAO;EAG1B,gBAAgB;EASV,cACJ,mBACA,eAAe,6BACf,SAAS,cACR;IAAU;;EAgBN,QACL,mBACA,gBACA,SAAS,cACR,cAAc;;EAmBjB,kBAAkB;EAIlB,WAAW;EAKL,YAAY,oBAAoB;;;;;UAYxB;EAWR,eAAe,oBAAoB;EAQnC,YAAY;UAeV"}
package/dist/index.mjs ADDED
@@ -0,0 +1,3 @@
1
+ import "./rolldown-runtime-ClRpJifh.mjs";
2
+ import { a as parseHarnessRequest, i as MAX_PROTOCOL_LINE_BYTES, n as HarnessSessionService, o as PiHarnessBackend, r as MAX_PROMPT_LENGTH, t as FileResumeStateStore } from "./session-store-BUSm7uRt.mjs";
3
+ export { FileResumeStateStore, HarnessSessionService, MAX_PROMPT_LENGTH, MAX_PROTOCOL_LINE_BYTES, PiHarnessBackend, parseHarnessRequest };
@@ -0,0 +1,3 @@
1
+ import "node:module";
2
+ //#endregion
3
+ export {};
@@ -0,0 +1,390 @@
1
+ import { createPi } from "@ai-sdk/harness-pi";
2
+ import { HarnessAgent } from "@ai-sdk/harness/agent";
3
+ import { createJustBashSandbox } from "@ai-sdk/sandbox-just-bash";
4
+ import { mkdir, readFile, rm } from "node:fs/promises";
5
+ import { dirname, join } from "node:path";
6
+ import { writeFileAtomic } from "@pairdraw/core/node/fs";
7
+ //#region src/backends/pi.ts
8
+ function asJSONValue(value) {
9
+ if (value === void 0 || typeof value === "bigint" || typeof value === "function") return null;
10
+ try {
11
+ const clone = structuredClone(value);
12
+ JSON.stringify(clone);
13
+ return clone;
14
+ } catch {
15
+ return null;
16
+ }
17
+ }
18
+ function mapPart(part) {
19
+ if (part.type === "text-delta") return {
20
+ type: "text-delta",
21
+ text: part.text
22
+ };
23
+ if (part.type === "reasoning-delta") return {
24
+ type: "reasoning-delta",
25
+ text: part.text
26
+ };
27
+ if (part.type === "tool-call") return {
28
+ type: "tool-call",
29
+ toolCallId: part.toolCallId,
30
+ toolName: part.toolName,
31
+ input: asJSONValue(part.input)
32
+ };
33
+ if (part.type === "tool-result") return {
34
+ type: "tool-result",
35
+ toolCallId: part.toolCallId,
36
+ toolName: part.toolName,
37
+ output: asJSONValue(part.output)
38
+ };
39
+ if (part.type === "finish") {
40
+ const usage = part.totalUsage;
41
+ return {
42
+ type: "finish",
43
+ finishReason: part.finishReason,
44
+ usage: {
45
+ inputTokens: usage.inputTokens ?? null,
46
+ outputTokens: usage.outputTokens ?? null,
47
+ cacheReadTokens: usage.inputTokenDetails.cacheReadTokens ?? null,
48
+ cacheWriteTokens: usage.inputTokenDetails.cacheWriteTokens ?? null
49
+ }
50
+ };
51
+ }
52
+ if (part.type === "error") return {
53
+ type: "error",
54
+ message: part.error instanceof Error ? part.error.message : String(part.error)
55
+ };
56
+ }
57
+ var PiBackendSession = class {
58
+ agent;
59
+ session;
60
+ sessionId;
61
+ isResume;
62
+ constructor(agent, session) {
63
+ this.agent = agent;
64
+ this.session = session;
65
+ this.sessionId = session.sessionId;
66
+ this.isResume = session.isResume;
67
+ }
68
+ async *runTurn(prompt, signal) {
69
+ const result = await this.agent.stream({
70
+ session: this.session,
71
+ prompt,
72
+ abortSignal: signal
73
+ });
74
+ for await (const part of result.fullStream) {
75
+ const event = mapPart(part);
76
+ if (event) yield event;
77
+ }
78
+ }
79
+ async stop() {
80
+ return await this.session.stop();
81
+ }
82
+ async destroy() {
83
+ await this.session.destroy();
84
+ }
85
+ };
86
+ var PiHarnessBackend = class {
87
+ defaults;
88
+ id = "pi";
89
+ capabilities = {
90
+ adapter: "pi",
91
+ sandboxes: ["just-bash"],
92
+ structuredOutput: false,
93
+ sessionResume: "live-process",
94
+ turnContinuation: true
95
+ };
96
+ constructor(defaults = {}) {
97
+ this.defaults = defaults;
98
+ }
99
+ async createSession(options) {
100
+ const configuration = options.configuration;
101
+ if (!configuration) throw new Error("Harness configuration is required");
102
+ const thinkingLevel = typeof configuration.settings?.thinkingLevel === "string" ? configuration.settings.thinkingLevel : void 0;
103
+ const permissionMode = typeof configuration.settings?.permissionMode === "string" ? configuration.settings.permissionMode : void 0;
104
+ const auth = this.defaults.auth ?? (this.defaults.apiKey ? { AI_GATEWAY_API_KEY: this.defaults.apiKey } : void 0);
105
+ const harness = createPi({
106
+ auth,
107
+ thinkingLevel: thinkingLevel ?? this.defaults.thinkingLevel,
108
+ agentDir: this.defaults.agentDir,
109
+ mcpServers: configuration.mcpServers ?? this.defaults.mcpServers
110
+ });
111
+ const agent = new HarnessAgent({
112
+ harness,
113
+ model: configuration.model,
114
+ sandbox: createJustBashSandbox({ cwd: "/workspace" }),
115
+ sandboxConfig: { workDir: "workspace" },
116
+ instructions: configuration.instructions ?? this.defaults.instructions,
117
+ skills: configuration.skills ?? [],
118
+ permissionMode: permissionMode ?? this.defaults.permissionMode ?? "allow-edits"
119
+ });
120
+ const sessionOptions = { sessionId: options.sessionId };
121
+ if (options.resumeState !== void 0) sessionOptions.resumeFrom = options.resumeState;
122
+ if (options.signal !== void 0) sessionOptions.abortSignal = options.signal;
123
+ return new PiBackendSession(agent, await agent.createSession(sessionOptions));
124
+ }
125
+ };
126
+ //#endregion
127
+ //#region src/protocol.ts
128
+ const HARNESS_ADAPTER_IDS = ["pi"];
129
+ const HARNESS_SANDBOX_IDS = ["just-bash"];
130
+ const MAX_PROTOCOL_LINE_BYTES = 1048576;
131
+ const MAX_PROMPT_LENGTH = 262144;
132
+ function isRecord(value) {
133
+ return typeof value === "object" && value !== null && !Array.isArray(value);
134
+ }
135
+ function requireString(record, key) {
136
+ const value = record[key];
137
+ if (typeof value !== "string" || value.length === 0) throw new Error(`Expected non-empty string at ${key}`);
138
+ return value;
139
+ }
140
+ function isAdapterID(value) {
141
+ return typeof value === "string" && HARNESS_ADAPTER_IDS.includes(value);
142
+ }
143
+ function isSandboxID(value) {
144
+ return typeof value === "string" && HARNESS_SANDBOX_IDS.includes(value);
145
+ }
146
+ function parseJSONRecord(value, field) {
147
+ if (value === void 0) return void 0;
148
+ if (!isRecord(value)) throw new Error(`Expected object at ${field}`);
149
+ try {
150
+ JSON.stringify(value);
151
+ return structuredClone(value);
152
+ } catch {
153
+ throw new Error(`Expected JSON-compatible object at ${field}`);
154
+ }
155
+ }
156
+ function parseSkillFile(value, field) {
157
+ if (!isRecord(value) || typeof value.content !== "string") throw new Error(`Expected skill file at ${field}`);
158
+ return {
159
+ path: requireString(value, "path"),
160
+ content: value.content
161
+ };
162
+ }
163
+ function parseSkills(value) {
164
+ if (value === void 0) return void 0;
165
+ if (!Array.isArray(value)) throw new Error("Expected array at skills");
166
+ return value.map((skill, index) => {
167
+ const field = `skills[${index}]`;
168
+ if (!isRecord(skill) || typeof skill.content !== "string") throw new Error(`Expected skill at ${field}`);
169
+ const parsed = {
170
+ name: requireString(skill, "name"),
171
+ description: requireString(skill, "description"),
172
+ content: skill.content
173
+ };
174
+ if (skill.files !== void 0) {
175
+ if (!Array.isArray(skill.files)) throw new Error(`Expected array at ${field}.files`);
176
+ parsed.files = skill.files.map((file, fileIndex) => parseSkillFile(file, `${field}.files[${fileIndex}]`));
177
+ }
178
+ return parsed;
179
+ });
180
+ }
181
+ function parseConfiguration(value) {
182
+ if (!isRecord(value)) throw new Error("Expected Harness session configuration");
183
+ if (!isAdapterID(value.adapter)) throw new Error("Unknown Harness adapter");
184
+ if (!isSandboxID(value.sandbox)) throw new Error("Unknown Harness sandbox");
185
+ const mcpServers = parseJSONRecord(value.mcpServers, "mcpServers");
186
+ const settings = parseJSONRecord(value.settings, "settings");
187
+ const configuration = {
188
+ adapter: value.adapter,
189
+ sandbox: value.sandbox,
190
+ model: requireString(value, "model")
191
+ };
192
+ if (settings) configuration.settings = settings;
193
+ if (mcpServers) configuration.mcpServers = mcpServers;
194
+ if (typeof value.instructions === "string") configuration.instructions = value.instructions;
195
+ const skills = parseSkills(value.skills);
196
+ if (skills) configuration.skills = skills;
197
+ return configuration;
198
+ }
199
+ function parseSessionParams(value) {
200
+ if (!isRecord(value)) throw new Error("Expected request params");
201
+ return { sessionId: requireString(value, "sessionId") };
202
+ }
203
+ function parseHarnessRequest(line) {
204
+ if (Buffer.byteLength(line, "utf8") > 1048576) throw new Error("Harness request exceeds the protocol size limit");
205
+ const parsed = JSON.parse(line);
206
+ if (!isRecord(parsed)) throw new Error("Expected a request object");
207
+ const id = requireString(parsed, "id");
208
+ const method = requireString(parsed, "method");
209
+ if (method === "service.capabilities" || method === "service.shutdown") return {
210
+ id,
211
+ method,
212
+ params: {}
213
+ };
214
+ if (method === "session.create") {
215
+ const params = parseSessionParams(parsed.params);
216
+ if (!isRecord(parsed.params)) throw new Error("Expected request params");
217
+ return {
218
+ id,
219
+ method,
220
+ params: {
221
+ ...params,
222
+ configuration: parseConfiguration(parsed.params.configuration)
223
+ }
224
+ };
225
+ }
226
+ if (method === "session.cancel" || method === "session.stop" || method === "session.destroy") return {
227
+ id,
228
+ method,
229
+ params: parseSessionParams(parsed.params)
230
+ };
231
+ if (method === "session.turn") {
232
+ if (!isRecord(parsed.params)) throw new Error("Expected request params");
233
+ const sessionId = requireString(parsed.params, "sessionId");
234
+ const prompt = requireString(parsed.params, "prompt");
235
+ if (prompt.length > 262144) throw new Error("Harness prompt exceeds the size limit");
236
+ return {
237
+ id,
238
+ method,
239
+ params: {
240
+ sessionId,
241
+ prompt
242
+ }
243
+ };
244
+ }
245
+ throw new Error(`Unknown harness method: ${method}`);
246
+ }
247
+ //#endregion
248
+ //#region src/service.ts
249
+ var HarnessSessionService = class {
250
+ backends;
251
+ store;
252
+ sessions = /* @__PURE__ */ new Map();
253
+ turns = /* @__PURE__ */ new Map();
254
+ /** Sessions whose last turn ended because it was cancelled. */
255
+ cancelled = /* @__PURE__ */ new Set();
256
+ constructor(backends, store) {
257
+ this.backends = backends;
258
+ this.store = store;
259
+ }
260
+ capabilities() {
261
+ return this.backends.size ? [...this.backends.values()].map((backend) => ({
262
+ ...backend.capabilities,
263
+ sandboxes: [...backend.capabilities.sandboxes]
264
+ })) : [];
265
+ }
266
+ async createSession(sessionId, configuration, signal) {
267
+ if (this.sessions.has(sessionId)) throw new Error(`Harness session already active: ${sessionId}`);
268
+ const backend = this.backends.get(configuration.adapter);
269
+ if (!backend) throw new Error(`Harness adapter is unavailable: ${configuration.adapter}`);
270
+ const resumeState = await this.loadResumeState(sessionId, backend);
271
+ const session = await backend.createSession({
272
+ sessionId,
273
+ resumeState,
274
+ configuration,
275
+ signal
276
+ });
277
+ this.sessions.set(sessionId, session);
278
+ return { isResume: session.isResume };
279
+ }
280
+ async *runTurn(sessionId, prompt, signal) {
281
+ const session = this.requireSession(sessionId);
282
+ if (this.turns.has(sessionId)) throw new Error(`Harness turn already active: ${sessionId}`);
283
+ const controller = new AbortController();
284
+ this.turns.set(sessionId, controller);
285
+ const abort = () => controller.abort();
286
+ if (signal?.aborted) abort();
287
+ else signal?.addEventListener("abort", abort, { once: true });
288
+ try {
289
+ yield* session.runTurn(prompt, controller.signal);
290
+ } finally {
291
+ signal?.removeEventListener("abort", abort);
292
+ if (this.turns.get(sessionId) === controller) this.turns.delete(sessionId);
293
+ if (controller.signal.aborted) this.cancelled.add(sessionId);
294
+ else this.cancelled.delete(sessionId);
295
+ }
296
+ }
297
+ /** Whether the session's last turn ended because it was cancelled, not because it finished. */
298
+ lastTurnCancelled(sessionId) {
299
+ return this.cancelled.has(sessionId);
300
+ }
301
+ cancelTurn(sessionId) {
302
+ this.requireSession(sessionId);
303
+ this.turns.get(sessionId)?.abort();
304
+ }
305
+ async stopSession(sessionId) {
306
+ const state = await this.requireSession(sessionId).stop();
307
+ await this.store.save(sessionId, state);
308
+ this.sessions.delete(sessionId);
309
+ this.cancelled.delete(sessionId);
310
+ }
311
+ /**
312
+ * A backend that resumes only within its live process (Pi's in-memory just-bash sandbox)
313
+ * cannot use saved state, and passing it makes every later session with that ID fail.
314
+ */
315
+ async loadResumeState(sessionId, backend) {
316
+ const resumeState = await this.store.load(sessionId);
317
+ if (resumeState && resumeState.harnessId !== backend.id) throw new Error(`Harness state belongs to ${resumeState.harnessId}, not ${backend.id}`);
318
+ if (backend.capabilities.sessionResume === "persistent") return resumeState;
319
+ await this.store.remove(sessionId);
320
+ }
321
+ async destroySession(sessionId) {
322
+ await this.requireSession(sessionId).destroy();
323
+ await this.store.remove(sessionId);
324
+ this.sessions.delete(sessionId);
325
+ this.cancelled.delete(sessionId);
326
+ }
327
+ async shutdown() {
328
+ const sessions = [...this.sessions.entries()];
329
+ const errors = (await Promise.allSettled(sessions.map(async ([sessionId, session]) => {
330
+ const state = await session.stop();
331
+ await this.store.save(sessionId, state);
332
+ this.sessions.delete(sessionId);
333
+ }))).filter((result) => result.status === "rejected").map((result) => result.reason);
334
+ if (errors.length) throw new AggregateError(errors, "Harness shutdown failed");
335
+ }
336
+ requireSession(sessionId) {
337
+ const session = this.sessions.get(sessionId);
338
+ if (!session) throw new Error(`Harness session is not active: ${sessionId}`);
339
+ return session;
340
+ }
341
+ };
342
+ //#endregion
343
+ //#region src/session-store.ts
344
+ const MAX_RESUME_STATE_BYTES = 1048576;
345
+ const SESSION_ID_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
346
+ function statePath(root, sessionId) {
347
+ if (!SESSION_ID_PATTERN.test(sessionId)) throw new Error("Invalid harness session ID");
348
+ return join(root, `${sessionId}.json`);
349
+ }
350
+ function isResumeState(value) {
351
+ if (typeof value !== "object" || value === null || !("type" in value)) return false;
352
+ if (!("harnessId" in value) || !("specificationVersion" in value) || !("data" in value)) return false;
353
+ return value.type === "resume-session" && typeof value.harnessId === "string" && value.specificationVersion === "harness-v1";
354
+ }
355
+ var FileResumeStateStore = class {
356
+ root;
357
+ constructor(root) {
358
+ this.root = root;
359
+ }
360
+ async load(sessionId) {
361
+ const path = statePath(this.root, sessionId);
362
+ try {
363
+ const content = await readFile(path, "utf8");
364
+ if (Buffer.byteLength(content, "utf8") > MAX_RESUME_STATE_BYTES) throw new Error("Persisted harness state exceeds the size limit");
365
+ const parsed = JSON.parse(content);
366
+ if (!isResumeState(parsed)) throw new Error("Persisted harness state is invalid");
367
+ return parsed;
368
+ } catch (error) {
369
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") return;
370
+ throw error;
371
+ }
372
+ }
373
+ async save(sessionId, state) {
374
+ const path = statePath(this.root, sessionId);
375
+ const content = JSON.stringify(state);
376
+ if (Buffer.byteLength(content, "utf8") > MAX_RESUME_STATE_BYTES) throw new Error("Harness state exceeds the persistence size limit");
377
+ await mkdir(dirname(path), {
378
+ recursive: true,
379
+ mode: 448
380
+ });
381
+ await writeFileAtomic(path, content, { mode: 384 });
382
+ }
383
+ async remove(sessionId) {
384
+ await rm(statePath(this.root, sessionId), { force: true });
385
+ }
386
+ };
387
+ //#endregion
388
+ export { parseHarnessRequest as a, MAX_PROTOCOL_LINE_BYTES as i, HarnessSessionService as n, PiHarnessBackend as o, MAX_PROMPT_LENGTH as r, FileResumeStateStore as t };
389
+
390
+ //# sourceMappingURL=session-store-BUSm7uRt.mjs.map