@pairdraw/harness 0.0.0-stage → 0.16.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/LICENSE +21 -0
- package/README.md +17 -2
- package/dist/index.d.mts +249 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +3 -0
- package/dist/rolldown-runtime-ClRpJifh.mjs +3 -0
- package/dist/session-store-BUSm7uRt.mjs +390 -0
- package/dist/session-store-BUSm7uRt.mjs.map +1 -0
- package/dist/stdio.d.mts +1 -0
- package/dist/stdio.mjs +198 -0
- package/dist/stdio.mjs.map +1 -0
- package/package.json +35 -4
- package/src/backends/pi.ts +165 -0
- package/src/backends/types.ts +42 -0
- package/src/index.ts +24 -0
- package/src/output.ts +15 -0
- package/src/protocol.ts +201 -0
- package/src/service.ts +128 -0
- package/src/session-store.ts +73 -0
- package/src/stdio.ts +153 -0
- package/src/typescript-dependencies.ts +30 -0
package/src/protocol.ts
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
type JSONPrimitive = null | boolean | number | string
|
|
2
|
+
export type JSONValue = JSONPrimitive | JSONValue[] | { [key: string]: JSONValue }
|
|
3
|
+
|
|
4
|
+
const HARNESS_ADAPTER_IDS = ['pi'] as const
|
|
5
|
+
const HARNESS_SANDBOX_IDS = ['just-bash'] as const
|
|
6
|
+
|
|
7
|
+
export type HarnessAdapterID = (typeof HARNESS_ADAPTER_IDS)[number]
|
|
8
|
+
export type HarnessSandboxID = (typeof HARNESS_SANDBOX_IDS)[number]
|
|
9
|
+
|
|
10
|
+
export interface HarnessSessionConfiguration {
|
|
11
|
+
adapter: HarnessAdapterID
|
|
12
|
+
sandbox: HarnessSandboxID
|
|
13
|
+
model: string
|
|
14
|
+
settings?: Record<string, JSONValue>
|
|
15
|
+
mcpServers?: Record<string, Record<string, JSONValue>>
|
|
16
|
+
instructions?: string
|
|
17
|
+
skills?: HarnessSkill[]
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** A skill the agent may load: its SKILL.md body and the text files beside it. */
|
|
21
|
+
export interface HarnessSkill {
|
|
22
|
+
name: string
|
|
23
|
+
description: string
|
|
24
|
+
content: string
|
|
25
|
+
files?: { path: string; content: string }[]
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface HarnessProviderCapability {
|
|
29
|
+
adapter: HarnessAdapterID
|
|
30
|
+
sandboxes: readonly HarnessSandboxID[]
|
|
31
|
+
structuredOutput: boolean
|
|
32
|
+
sessionResume: 'live-process' | 'persistent'
|
|
33
|
+
turnContinuation: boolean
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
interface HarnessTurnInput {
|
|
37
|
+
sessionId: string
|
|
38
|
+
prompt: string
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export type HarnessRequest =
|
|
42
|
+
| {
|
|
43
|
+
id: string
|
|
44
|
+
method: 'service.capabilities'
|
|
45
|
+
params?: Record<string, never>
|
|
46
|
+
}
|
|
47
|
+
| {
|
|
48
|
+
id: string
|
|
49
|
+
method: 'session.create'
|
|
50
|
+
params: { sessionId: string; configuration: HarnessSessionConfiguration }
|
|
51
|
+
}
|
|
52
|
+
| { id: string; method: 'session.turn'; params: HarnessTurnInput }
|
|
53
|
+
| { id: string; method: 'session.cancel'; params: { sessionId: string } }
|
|
54
|
+
| { id: string; method: 'session.stop'; params: { sessionId: string } }
|
|
55
|
+
| { id: string; method: 'session.destroy'; params: { sessionId: string } }
|
|
56
|
+
| { id: string; method: 'service.shutdown'; params?: Record<string, never> }
|
|
57
|
+
|
|
58
|
+
/** A turn's tokens; input counts cached tokens too, which the cache fields break out. */
|
|
59
|
+
export interface HarnessTurnUsage {
|
|
60
|
+
inputTokens: number | null
|
|
61
|
+
outputTokens: number | null
|
|
62
|
+
cacheReadTokens: number | null
|
|
63
|
+
cacheWriteTokens: number | null
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export type HarnessTurnEvent =
|
|
67
|
+
| { type: 'text-delta'; text: string }
|
|
68
|
+
| { type: 'reasoning-delta'; text: string }
|
|
69
|
+
| { type: 'tool-call'; toolCallId: string; toolName: string; input: JSONValue }
|
|
70
|
+
| { type: 'tool-result'; toolCallId: string; toolName: string; output: JSONValue }
|
|
71
|
+
| { type: 'finish'; finishReason: string; usage?: HarnessTurnUsage }
|
|
72
|
+
| { type: 'error'; message: string }
|
|
73
|
+
|
|
74
|
+
export type HarnessSidecarMessage =
|
|
75
|
+
| { type: 'response'; id: string; result?: JSONValue; error?: string }
|
|
76
|
+
| { type: 'turn.event'; id: string; event: HarnessTurnEvent }
|
|
77
|
+
|
|
78
|
+
export const MAX_PROTOCOL_LINE_BYTES = 1024 * 1024
|
|
79
|
+
export const MAX_PROMPT_LENGTH = 256 * 1024
|
|
80
|
+
|
|
81
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
82
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function requireString(record: Record<string, unknown>, key: string): string {
|
|
86
|
+
const value = record[key]
|
|
87
|
+
if (typeof value !== 'string' || value.length === 0) {
|
|
88
|
+
throw new Error(`Expected non-empty string at ${key}`)
|
|
89
|
+
}
|
|
90
|
+
return value
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function isAdapterID(value: unknown): value is HarnessAdapterID {
|
|
94
|
+
return typeof value === 'string' && HARNESS_ADAPTER_IDS.includes(value as HarnessAdapterID)
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function isSandboxID(value: unknown): value is HarnessSandboxID {
|
|
98
|
+
return typeof value === 'string' && HARNESS_SANDBOX_IDS.includes(value as HarnessSandboxID)
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function parseJSONRecord(value: unknown, field: string): Record<string, JSONValue> | undefined {
|
|
102
|
+
if (value === undefined) return undefined
|
|
103
|
+
if (!isRecord(value)) throw new Error(`Expected object at ${field}`)
|
|
104
|
+
try {
|
|
105
|
+
JSON.stringify(value)
|
|
106
|
+
return structuredClone(value) as Record<string, JSONValue>
|
|
107
|
+
} catch {
|
|
108
|
+
throw new Error(`Expected JSON-compatible object at ${field}`)
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function parseSkillFile(value: unknown, field: string): { path: string; content: string } {
|
|
113
|
+
if (!isRecord(value) || typeof value.content !== 'string') {
|
|
114
|
+
throw new Error(`Expected skill file at ${field}`)
|
|
115
|
+
}
|
|
116
|
+
return { path: requireString(value, 'path'), content: value.content }
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function parseSkills(value: unknown): HarnessSkill[] | undefined {
|
|
120
|
+
if (value === undefined) return undefined
|
|
121
|
+
if (!Array.isArray(value)) throw new Error('Expected array at skills')
|
|
122
|
+
return value.map((skill: unknown, index) => {
|
|
123
|
+
const field = `skills[${index}]`
|
|
124
|
+
if (!isRecord(skill) || typeof skill.content !== 'string') {
|
|
125
|
+
throw new Error(`Expected skill at ${field}`)
|
|
126
|
+
}
|
|
127
|
+
const parsed: HarnessSkill = {
|
|
128
|
+
name: requireString(skill, 'name'),
|
|
129
|
+
description: requireString(skill, 'description'),
|
|
130
|
+
content: skill.content
|
|
131
|
+
}
|
|
132
|
+
if (skill.files !== undefined) {
|
|
133
|
+
if (!Array.isArray(skill.files)) throw new Error(`Expected array at ${field}.files`)
|
|
134
|
+
parsed.files = skill.files.map((file: unknown, fileIndex) =>
|
|
135
|
+
parseSkillFile(file, `${field}.files[${fileIndex}]`)
|
|
136
|
+
)
|
|
137
|
+
}
|
|
138
|
+
return parsed
|
|
139
|
+
})
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function parseConfiguration(value: unknown): HarnessSessionConfiguration {
|
|
143
|
+
if (!isRecord(value)) throw new Error('Expected Harness session configuration')
|
|
144
|
+
if (!isAdapterID(value.adapter)) throw new Error('Unknown Harness adapter')
|
|
145
|
+
if (!isSandboxID(value.sandbox)) throw new Error('Unknown Harness sandbox')
|
|
146
|
+
const mcpServers = parseJSONRecord(value.mcpServers, 'mcpServers')
|
|
147
|
+
const settings = parseJSONRecord(value.settings, 'settings')
|
|
148
|
+
const configuration: HarnessSessionConfiguration = {
|
|
149
|
+
adapter: value.adapter,
|
|
150
|
+
sandbox: value.sandbox,
|
|
151
|
+
model: requireString(value, 'model')
|
|
152
|
+
}
|
|
153
|
+
if (settings) configuration.settings = settings
|
|
154
|
+
if (mcpServers) {
|
|
155
|
+
configuration.mcpServers = mcpServers as Record<string, Record<string, JSONValue>>
|
|
156
|
+
}
|
|
157
|
+
if (typeof value.instructions === 'string') configuration.instructions = value.instructions
|
|
158
|
+
const skills = parseSkills(value.skills)
|
|
159
|
+
if (skills) configuration.skills = skills
|
|
160
|
+
return configuration
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function parseSessionParams(value: unknown): { sessionId: string } {
|
|
164
|
+
if (!isRecord(value)) throw new Error('Expected request params')
|
|
165
|
+
return { sessionId: requireString(value, 'sessionId') }
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export function parseHarnessRequest(line: string): HarnessRequest {
|
|
169
|
+
if (Buffer.byteLength(line, 'utf8') > MAX_PROTOCOL_LINE_BYTES) {
|
|
170
|
+
throw new Error('Harness request exceeds the protocol size limit')
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const parsed: unknown = JSON.parse(line)
|
|
174
|
+
if (!isRecord(parsed)) throw new Error('Expected a request object')
|
|
175
|
+
const id = requireString(parsed, 'id')
|
|
176
|
+
const method = requireString(parsed, 'method')
|
|
177
|
+
|
|
178
|
+
if (method === 'service.capabilities' || method === 'service.shutdown') {
|
|
179
|
+
return { id, method, params: {} }
|
|
180
|
+
}
|
|
181
|
+
if (method === 'session.create') {
|
|
182
|
+
const params = parseSessionParams(parsed.params)
|
|
183
|
+
if (!isRecord(parsed.params)) throw new Error('Expected request params')
|
|
184
|
+
return {
|
|
185
|
+
id,
|
|
186
|
+
method,
|
|
187
|
+
params: { ...params, configuration: parseConfiguration(parsed.params.configuration) }
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
if (method === 'session.cancel' || method === 'session.stop' || method === 'session.destroy') {
|
|
191
|
+
return { id, method, params: parseSessionParams(parsed.params) }
|
|
192
|
+
}
|
|
193
|
+
if (method === 'session.turn') {
|
|
194
|
+
if (!isRecord(parsed.params)) throw new Error('Expected request params')
|
|
195
|
+
const sessionId = requireString(parsed.params, 'sessionId')
|
|
196
|
+
const prompt = requireString(parsed.params, 'prompt')
|
|
197
|
+
if (prompt.length > MAX_PROMPT_LENGTH) throw new Error('Harness prompt exceeds the size limit')
|
|
198
|
+
return { id, method, params: { sessionId, prompt } }
|
|
199
|
+
}
|
|
200
|
+
throw new Error(`Unknown harness method: ${method}`)
|
|
201
|
+
}
|
package/src/service.ts
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import type { BackendEvent, BackendSession, HarnessBackend } from './backends/types'
|
|
2
|
+
import type { HarnessSessionConfiguration, JSONValue } from './protocol'
|
|
3
|
+
import type { ResumeStateStore } from './session-store'
|
|
4
|
+
|
|
5
|
+
export class HarnessSessionService {
|
|
6
|
+
private readonly sessions = new Map<string, BackendSession>()
|
|
7
|
+
private readonly turns = new Map<string, AbortController>()
|
|
8
|
+
/** Sessions whose last turn ended because it was cancelled. */
|
|
9
|
+
private readonly cancelled = new Set<string>()
|
|
10
|
+
|
|
11
|
+
constructor(
|
|
12
|
+
private readonly backends: ReadonlyMap<string, HarnessBackend>,
|
|
13
|
+
private readonly store: ResumeStateStore
|
|
14
|
+
) {}
|
|
15
|
+
|
|
16
|
+
capabilities(): JSONValue {
|
|
17
|
+
return this.backends.size
|
|
18
|
+
? [...this.backends.values()].map((backend) => ({
|
|
19
|
+
...backend.capabilities,
|
|
20
|
+
sandboxes: [...backend.capabilities.sandboxes]
|
|
21
|
+
}))
|
|
22
|
+
: []
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async createSession(
|
|
26
|
+
sessionId: string,
|
|
27
|
+
configuration: HarnessSessionConfiguration,
|
|
28
|
+
signal?: AbortSignal
|
|
29
|
+
): Promise<{ isResume: boolean }> {
|
|
30
|
+
if (this.sessions.has(sessionId))
|
|
31
|
+
throw new Error(`Harness session already active: ${sessionId}`)
|
|
32
|
+
const backend = this.backends.get(configuration.adapter)
|
|
33
|
+
if (!backend) throw new Error(`Harness adapter is unavailable: ${configuration.adapter}`)
|
|
34
|
+
const resumeState = await this.loadResumeState(sessionId, backend)
|
|
35
|
+
const session = await backend.createSession({
|
|
36
|
+
sessionId,
|
|
37
|
+
resumeState,
|
|
38
|
+
configuration,
|
|
39
|
+
signal
|
|
40
|
+
})
|
|
41
|
+
this.sessions.set(sessionId, session)
|
|
42
|
+
return { isResume: session.isResume }
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async *runTurn(
|
|
46
|
+
sessionId: string,
|
|
47
|
+
prompt: string,
|
|
48
|
+
signal?: AbortSignal
|
|
49
|
+
): AsyncIterable<BackendEvent> {
|
|
50
|
+
const session = this.requireSession(sessionId)
|
|
51
|
+
if (this.turns.has(sessionId)) throw new Error(`Harness turn already active: ${sessionId}`)
|
|
52
|
+
const controller = new AbortController()
|
|
53
|
+
this.turns.set(sessionId, controller)
|
|
54
|
+
const abort = () => controller.abort()
|
|
55
|
+
if (signal?.aborted) abort()
|
|
56
|
+
else signal?.addEventListener('abort', abort, { once: true })
|
|
57
|
+
try {
|
|
58
|
+
yield* session.runTurn(prompt, controller.signal)
|
|
59
|
+
} finally {
|
|
60
|
+
signal?.removeEventListener('abort', abort)
|
|
61
|
+
if (this.turns.get(sessionId) === controller) this.turns.delete(sessionId)
|
|
62
|
+
if (controller.signal.aborted) this.cancelled.add(sessionId)
|
|
63
|
+
else this.cancelled.delete(sessionId)
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Whether the session's last turn ended because it was cancelled, not because it finished. */
|
|
68
|
+
lastTurnCancelled(sessionId: string): boolean {
|
|
69
|
+
return this.cancelled.has(sessionId)
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
cancelTurn(sessionId: string): void {
|
|
73
|
+
this.requireSession(sessionId)
|
|
74
|
+
this.turns.get(sessionId)?.abort()
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
async stopSession(sessionId: string): Promise<void> {
|
|
78
|
+
const session = this.requireSession(sessionId)
|
|
79
|
+
const state = await session.stop()
|
|
80
|
+
await this.store.save(sessionId, state)
|
|
81
|
+
this.sessions.delete(sessionId)
|
|
82
|
+
this.cancelled.delete(sessionId)
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* A backend that resumes only within its live process (Pi's in-memory just-bash sandbox)
|
|
87
|
+
* cannot use saved state, and passing it makes every later session with that ID fail.
|
|
88
|
+
*/
|
|
89
|
+
private async loadResumeState(sessionId: string, backend: HarnessBackend) {
|
|
90
|
+
const resumeState = await this.store.load(sessionId)
|
|
91
|
+
// State another backend saved stays for that backend to resume.
|
|
92
|
+
if (resumeState && resumeState.harnessId !== backend.id) {
|
|
93
|
+
throw new Error(`Harness state belongs to ${resumeState.harnessId}, not ${backend.id}`)
|
|
94
|
+
}
|
|
95
|
+
if (backend.capabilities.sessionResume === 'persistent') return resumeState
|
|
96
|
+
await this.store.remove(sessionId)
|
|
97
|
+
return undefined
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async destroySession(sessionId: string): Promise<void> {
|
|
101
|
+
const session = this.requireSession(sessionId)
|
|
102
|
+
await session.destroy()
|
|
103
|
+
await this.store.remove(sessionId)
|
|
104
|
+
this.sessions.delete(sessionId)
|
|
105
|
+
this.cancelled.delete(sessionId)
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async shutdown(): Promise<void> {
|
|
109
|
+
const sessions = [...this.sessions.entries()]
|
|
110
|
+
const results = await Promise.allSettled(
|
|
111
|
+
sessions.map(async ([sessionId, session]) => {
|
|
112
|
+
const state = await session.stop()
|
|
113
|
+
await this.store.save(sessionId, state)
|
|
114
|
+
this.sessions.delete(sessionId)
|
|
115
|
+
})
|
|
116
|
+
)
|
|
117
|
+
const errors = results
|
|
118
|
+
.filter((result) => result.status === 'rejected')
|
|
119
|
+
.map((result) => result.reason)
|
|
120
|
+
if (errors.length) throw new AggregateError(errors, 'Harness shutdown failed')
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
private requireSession(sessionId: string): BackendSession {
|
|
124
|
+
const session = this.sessions.get(sessionId)
|
|
125
|
+
if (!session) throw new Error(`Harness session is not active: ${sessionId}`)
|
|
126
|
+
return session
|
|
127
|
+
}
|
|
128
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { mkdir, readFile, rm } from 'node:fs/promises'
|
|
2
|
+
import { dirname, join } from 'node:path'
|
|
3
|
+
|
|
4
|
+
import { writeFileAtomic } from '@pairdraw/core/node/fs'
|
|
5
|
+
|
|
6
|
+
import type { HarnessResumeState } from './backends/types'
|
|
7
|
+
|
|
8
|
+
const MAX_RESUME_STATE_BYTES = 1024 * 1024
|
|
9
|
+
const SESSION_ID_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/
|
|
10
|
+
|
|
11
|
+
export interface ResumeStateStore {
|
|
12
|
+
load(sessionId: string): Promise<HarnessResumeState | undefined>
|
|
13
|
+
save(sessionId: string, state: HarnessResumeState): Promise<void>
|
|
14
|
+
remove(sessionId: string): Promise<void>
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function statePath(root: string, sessionId: string): string {
|
|
18
|
+
if (!SESSION_ID_PATTERN.test(sessionId)) throw new Error('Invalid harness session ID')
|
|
19
|
+
return join(root, `${sessionId}.json`)
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function isResumeState(value: unknown): value is HarnessResumeState {
|
|
23
|
+
if (typeof value !== 'object' || value === null || !('type' in value)) return false
|
|
24
|
+
if (!('harnessId' in value) || !('specificationVersion' in value) || !('data' in value)) {
|
|
25
|
+
return false
|
|
26
|
+
}
|
|
27
|
+
return (
|
|
28
|
+
value.type === 'resume-session' &&
|
|
29
|
+
typeof value.harnessId === 'string' &&
|
|
30
|
+
value.specificationVersion === 'harness-v1'
|
|
31
|
+
)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export class FileResumeStateStore implements ResumeStateStore {
|
|
35
|
+
constructor(private readonly root: string) {}
|
|
36
|
+
|
|
37
|
+
async load(sessionId: string): Promise<HarnessResumeState | undefined> {
|
|
38
|
+
const path = statePath(this.root, sessionId)
|
|
39
|
+
try {
|
|
40
|
+
const content = await readFile(path, 'utf8')
|
|
41
|
+
if (Buffer.byteLength(content, 'utf8') > MAX_RESUME_STATE_BYTES) {
|
|
42
|
+
throw new Error('Persisted harness state exceeds the size limit')
|
|
43
|
+
}
|
|
44
|
+
const parsed: unknown = JSON.parse(content)
|
|
45
|
+
if (!isResumeState(parsed)) throw new Error('Persisted harness state is invalid')
|
|
46
|
+
return parsed
|
|
47
|
+
} catch (error) {
|
|
48
|
+
if (
|
|
49
|
+
typeof error === 'object' &&
|
|
50
|
+
error !== null &&
|
|
51
|
+
'code' in error &&
|
|
52
|
+
error.code === 'ENOENT'
|
|
53
|
+
) {
|
|
54
|
+
return undefined
|
|
55
|
+
}
|
|
56
|
+
throw error
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async save(sessionId: string, state: HarnessResumeState): Promise<void> {
|
|
61
|
+
const path = statePath(this.root, sessionId)
|
|
62
|
+
const content = JSON.stringify(state)
|
|
63
|
+
if (Buffer.byteLength(content, 'utf8') > MAX_RESUME_STATE_BYTES) {
|
|
64
|
+
throw new Error('Harness state exceeds the persistence size limit')
|
|
65
|
+
}
|
|
66
|
+
await mkdir(dirname(path), { recursive: true, mode: 0o700 })
|
|
67
|
+
await writeFileAtomic(path, content, { mode: 0o600 })
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async remove(sessionId: string): Promise<void> {
|
|
71
|
+
await rm(statePath(this.root, sessionId), { force: true })
|
|
72
|
+
}
|
|
73
|
+
}
|
package/src/stdio.ts
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import { homedir } from 'node:os'
|
|
4
|
+
import { join } from 'node:path'
|
|
5
|
+
import { createInterface } from 'node:readline'
|
|
6
|
+
|
|
7
|
+
import { PiHarnessBackend } from '#harness/backends/pi'
|
|
8
|
+
import type { PiHarnessBackendOptions } from '#harness/backends/pi'
|
|
9
|
+
import { reserveProtocolOutput } from '#harness/output'
|
|
10
|
+
import type { HarnessRequest, HarnessSidecarMessage } from '#harness/protocol'
|
|
11
|
+
import { parseHarnessRequest } from '#harness/protocol'
|
|
12
|
+
import { HarnessSessionService } from '#harness/service'
|
|
13
|
+
import { FileResumeStateStore } from '#harness/session-store'
|
|
14
|
+
import { loadTypeScriptDependencies } from '#harness/typescript-dependencies'
|
|
15
|
+
|
|
16
|
+
import packageJSON from '../package.json' with { type: 'json' }
|
|
17
|
+
|
|
18
|
+
// The app reads this to check that the companion matches it, before anything else starts.
|
|
19
|
+
if (process.argv.includes('--version')) {
|
|
20
|
+
process.stdout.write(`${packageJSON.version}\n`)
|
|
21
|
+
process.exit(0)
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const writeProtocol = reserveProtocolOutput()
|
|
25
|
+
loadTypeScriptDependencies()
|
|
26
|
+
|
|
27
|
+
const stateRoot =
|
|
28
|
+
process.env.PAIRDRAW_HARNESS_STATE_DIR ?? join(homedir(), '.pairdraw', 'harness-sessions')
|
|
29
|
+
const agentDir = process.env.PAIRDRAW_HARNESS_AGENT_DIR
|
|
30
|
+
const apiKey = process.env.PAIRDRAW_HARNESS_API_KEY
|
|
31
|
+
const backendOptions: PiHarnessBackendOptions = {}
|
|
32
|
+
if (agentDir) backendOptions.agentDir = agentDir
|
|
33
|
+
if (apiKey) backendOptions.apiKey = apiKey
|
|
34
|
+
const backend = new PiHarnessBackend(backendOptions)
|
|
35
|
+
const service = new HarnessSessionService(
|
|
36
|
+
new Map([[backend.id, backend]]),
|
|
37
|
+
new FileResumeStateStore(stateRoot)
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
async function emit(message: HarnessSidecarMessage): Promise<void> {
|
|
41
|
+
if (writeProtocol(`${JSON.stringify(message)}\n`)) return
|
|
42
|
+
await new Promise<void>((resolve) => {
|
|
43
|
+
process.stdout.once('drain', resolve)
|
|
44
|
+
})
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function messageFor(error: unknown): string {
|
|
48
|
+
return error instanceof Error ? error.message : String(error)
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function dispatch(line: string): Promise<boolean> {
|
|
52
|
+
let requestId = 'unknown'
|
|
53
|
+
try {
|
|
54
|
+
const request = parseHarnessRequest(line)
|
|
55
|
+
requestId = request.id
|
|
56
|
+
if (request.method === 'service.capabilities') {
|
|
57
|
+
await emit({
|
|
58
|
+
type: 'response',
|
|
59
|
+
id: request.id,
|
|
60
|
+
result: service.capabilities()
|
|
61
|
+
})
|
|
62
|
+
return true
|
|
63
|
+
}
|
|
64
|
+
if (request.method === 'session.create') {
|
|
65
|
+
const result = await service.createSession(
|
|
66
|
+
request.params.sessionId,
|
|
67
|
+
request.params.configuration
|
|
68
|
+
)
|
|
69
|
+
await emit({
|
|
70
|
+
type: 'response',
|
|
71
|
+
id: request.id,
|
|
72
|
+
result: { isResume: result.isResume }
|
|
73
|
+
})
|
|
74
|
+
return true
|
|
75
|
+
}
|
|
76
|
+
if (request.method === 'session.turn') {
|
|
77
|
+
const { sessionId, prompt } = request.params
|
|
78
|
+
for await (const event of service.runTurn(sessionId, prompt)) {
|
|
79
|
+
await emit({ type: 'turn.event', id: request.id, event })
|
|
80
|
+
}
|
|
81
|
+
// A cancelled turn ends its stream quietly; its answer says it was cancelled.
|
|
82
|
+
const cancelled = service.lastTurnCancelled(sessionId)
|
|
83
|
+
await emit({
|
|
84
|
+
type: 'response',
|
|
85
|
+
id: request.id,
|
|
86
|
+
result: cancelled ? { cancelled: true } : { completed: true }
|
|
87
|
+
})
|
|
88
|
+
return true
|
|
89
|
+
}
|
|
90
|
+
if (request.method === 'session.cancel') {
|
|
91
|
+
service.cancelTurn(request.params.sessionId)
|
|
92
|
+
await emit({ type: 'response', id: request.id, result: { cancelled: true } })
|
|
93
|
+
return true
|
|
94
|
+
}
|
|
95
|
+
if (request.method === 'session.stop') {
|
|
96
|
+
await service.stopSession(request.params.sessionId)
|
|
97
|
+
await emit({ type: 'response', id: request.id, result: { stopped: true } })
|
|
98
|
+
return true
|
|
99
|
+
}
|
|
100
|
+
if (request.method === 'session.destroy') {
|
|
101
|
+
await service.destroySession(request.params.sessionId)
|
|
102
|
+
await emit({ type: 'response', id: request.id, result: { destroyed: true } })
|
|
103
|
+
return true
|
|
104
|
+
}
|
|
105
|
+
await service.shutdown()
|
|
106
|
+
await emit({ type: 'response', id: request.id, result: { shutdown: true } })
|
|
107
|
+
return false
|
|
108
|
+
} catch (error) {
|
|
109
|
+
await emit({ type: 'response', id: requestId, error: messageFor(error) })
|
|
110
|
+
return true
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const input = createInterface({ input: process.stdin, crlfDelay: Infinity })
|
|
115
|
+
let queue = Promise.resolve(true)
|
|
116
|
+
const activeTurns = new Set<Promise<boolean>>()
|
|
117
|
+
input.on('line', (line) => {
|
|
118
|
+
let request: HarnessRequest | undefined
|
|
119
|
+
try {
|
|
120
|
+
request = parseHarnessRequest(line)
|
|
121
|
+
} catch (error) {
|
|
122
|
+
console.warn('Deferring malformed Harness request to protocol error handling:', error)
|
|
123
|
+
}
|
|
124
|
+
if (request?.method === 'session.turn') {
|
|
125
|
+
const turn = dispatch(line).finally(() => activeTurns.delete(turn))
|
|
126
|
+
activeTurns.add(turn)
|
|
127
|
+
return
|
|
128
|
+
}
|
|
129
|
+
queue = queue.then(async (keepRunning) => {
|
|
130
|
+
if (!keepRunning) return false
|
|
131
|
+
const next = await dispatch(line)
|
|
132
|
+
if (!next) input.close()
|
|
133
|
+
return next
|
|
134
|
+
})
|
|
135
|
+
})
|
|
136
|
+
let closing: Promise<void> | undefined
|
|
137
|
+
async function closeSidecar(): Promise<void> {
|
|
138
|
+
closing ??= queue
|
|
139
|
+
.then(async () => {
|
|
140
|
+
await Promise.allSettled(activeTurns)
|
|
141
|
+
await service.shutdown()
|
|
142
|
+
return undefined
|
|
143
|
+
})
|
|
144
|
+
.catch((error) => {
|
|
145
|
+
process.stderr.write(`${messageFor(error)}\n`)
|
|
146
|
+
process.exitCode = 1
|
|
147
|
+
})
|
|
148
|
+
await closing
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
input.on('close', () => void closeSidecar())
|
|
152
|
+
process.on('SIGTERM', () => input.close())
|
|
153
|
+
process.on('SIGINT', () => input.close())
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs'
|
|
2
|
+
import { fileURLToPath } from 'node:url'
|
|
3
|
+
|
|
4
|
+
import { transformSync } from 'amaro'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* `@ai-sdk/harness-pi` imports `pi-mcp-adapter`, which publishes TypeScript sources, and Node
|
|
8
|
+
* refuses to strip types under `node_modules`. Transform them for TypeScript dependencies only, so
|
|
9
|
+
* Pi sessions with MCP servers start under Node; Bun runs TypeScript itself. The adapter uses
|
|
10
|
+
* parameter properties, which need Amaro's transform mode: Node 26 only strips types.
|
|
11
|
+
*/
|
|
12
|
+
export function loadTypeScriptDependencies(): void {
|
|
13
|
+
if (process.versions.bun) return
|
|
14
|
+
// Read at runtime so Node versions without module hooks still start the companion.
|
|
15
|
+
const { registerHooks } = process.getBuiltinModule('node:module')
|
|
16
|
+
if (typeof registerHooks !== 'function') return
|
|
17
|
+
registerHooks({
|
|
18
|
+
load(url, context, nextLoad) {
|
|
19
|
+
if (!url.startsWith('file:') || !url.endsWith('.ts') || !url.includes('/node_modules/')) {
|
|
20
|
+
return nextLoad(url, context)
|
|
21
|
+
}
|
|
22
|
+
const source = readFileSync(fileURLToPath(url), 'utf8')
|
|
23
|
+
return {
|
|
24
|
+
format: 'module',
|
|
25
|
+
source: transformSync(source, { mode: 'transform' }).code,
|
|
26
|
+
shortCircuit: true
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
})
|
|
30
|
+
}
|