@leitwerk-dev/test-support 0.1.2 → 0.1.3

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.
Files changed (47) hide show
  1. package/dist/compact-process-detail-fixture.js +73 -0
  2. package/dist/compact-process-detail-fixture.js.map +1 -0
  3. package/dist/fakes/fake-git-ops.js +101 -0
  4. package/dist/fakes/fake-git-ops.js.map +1 -0
  5. package/dist/fakes/fake-llm.js +27 -0
  6. package/dist/fakes/fake-llm.js.map +1 -0
  7. package/dist/fakes/index.js +2 -10
  8. package/dist/fakes/index.js.map +1 -1
  9. package/dist/fixtures.js +2 -35
  10. package/dist/fixtures.js.map +1 -1
  11. package/dist/in-process-worker.js +2 -0
  12. package/dist/in-process-worker.js.map +1 -0
  13. package/dist/index.js +12 -56
  14. package/dist/index.js.map +1 -1
  15. package/dist/integration-harness.js +38 -0
  16. package/dist/integration-harness.js.map +1 -0
  17. package/dist/integration.js +4 -19
  18. package/dist/integration.js.map +1 -1
  19. package/dist/polling.js +14 -0
  20. package/dist/polling.js.map +1 -0
  21. package/dist/question-fixtures.js +26 -0
  22. package/dist/question-fixtures.js.map +1 -0
  23. package/dist/server-extension-test-harness.js +167 -0
  24. package/dist/server-extension-test-harness.js.map +1 -0
  25. package/dist/stub-worker-entry.js +5 -9
  26. package/dist/stub-worker-entry.js.map +1 -1
  27. package/dist/test-app.js +47 -0
  28. package/dist/test-app.js.map +1 -0
  29. package/dist/worker-testing/in-process-worker-spawn.js +61 -0
  30. package/dist/worker-testing/in-process-worker-spawn.js.map +1 -0
  31. package/dist/worker-testing/index.js +7 -350
  32. package/dist/worker-testing/index.js.map +1 -1
  33. package/dist/worker-testing/ipc-harness.js +17 -0
  34. package/dist/worker-testing/ipc-harness.js.map +1 -0
  35. package/dist/worker-testing/schema-driven-stub-pi.js +65 -0
  36. package/dist/worker-testing/schema-driven-stub-pi.js.map +1 -0
  37. package/dist/worker-testing/stub-pi-controls.js +10 -0
  38. package/dist/worker-testing/stub-pi-controls.js.map +1 -0
  39. package/dist/worker-testing/stub-pi-tree-handle.js +515 -0
  40. package/dist/worker-testing/stub-pi-tree-handle.js.map +1 -0
  41. package/dist/worker-testing/worker-runtime-harness.js +216 -0
  42. package/dist/worker-testing/worker-runtime-harness.js.map +1 -0
  43. package/dist/worker-testing/worker-start-payload.js +101 -0
  44. package/dist/worker-testing/worker-start-payload.js.map +1 -0
  45. package/dist/workspace-source-aliases.js +126 -0
  46. package/dist/workspace-source-aliases.js.map +1 -0
  47. package/package.json +8 -8
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/worker-testing/worker-runtime-harness.ts","../../src/worker-testing/worker-start-payload.ts"],"sourcesContent":["import { createEventBus } from \"@leitwerk-dev/process-sdk\";\nimport {\n\tcreateWorkerRuntime,\n\ttype WorkerRuntimeAdapters,\n\ttype WorkerRuntimeConfig,\n\ttype WorkerRuntimeScheduler,\n} from \"@leitwerk-dev/worker\";\nimport {\n\tcreateIpcMessage,\n\ttype ServerToWorkerMessage,\n\ttype WorkerStartPayload,\n\ttype WorkerToServerMessage,\n} from \"@leitwerk-dev/worker-protocol\";\n\ntype Timer = ReturnType<typeof setTimeout>;\ntype ServerMessageType = ServerToWorkerMessage[\"type\"];\ntype ServerMessagePayloadByType = {\n\t[T in ServerMessageType]: Extract<ServerToWorkerMessage, { type: T }>[\"payload\"];\n};\ntype WorkerMessageType = WorkerToServerMessage[\"type\"];\ntype WorkerMessageByType<T extends WorkerMessageType> = Extract<WorkerToServerMessage, { type: T }>;\ntype MessageWaiter = {\n\ttype: WorkerMessageType;\n\tcount: number;\n\tresolve(message: WorkerToServerMessage): void;\n};\n\ntype Scheduled = {\n\tid: number;\n\tdueAt: number;\n\thandler(): void;\n};\n\nexport interface ManualWorkerRuntimeScheduler extends WorkerRuntimeScheduler {\n\tadvanceBy(delayMs: number): Promise<void>;\n\tpendingDelays(): number[];\n}\n\nexport function createManualWorkerRuntimeScheduler(\n\tinitialNow = new Date(\"2025-01-01T00:00:00.000Z\"),\n): ManualWorkerRuntimeScheduler {\n\tlet nowMs = initialNow.getTime();\n\tlet nextId = 1;\n\tconst scheduled = new Map<number, Scheduled>();\n\tconst asTimer = (id: number) => id as unknown as Timer;\n\tconst fromTimer = (timer: Timer) => timer as unknown as number;\n\n\tconst schedule = (handler: () => void, delayMs: number): number => {\n\t\tconst id = nextId++;\n\t\tscheduled.set(id, { id, dueAt: nowMs + delayMs, handler });\n\t\treturn id;\n\t};\n\tconst clearTimer = (timer: Timer): void => {\n\t\tscheduled.delete(fromTimer(timer));\n\t};\n\n\treturn {\n\t\tsetTimeout: (handler, delayMs) => asTimer(schedule(handler, delayMs)),\n\t\tclearTimeout: clearTimer,\n\t\tsleep: (delayMs) => new Promise((resolve) => schedule(resolve, delayMs)),\n\t\tnow() {\n\t\t\treturn new Date(nowMs);\n\t\t},\n\t\tpendingDelays() {\n\t\t\treturn [...scheduled.values()]\n\t\t\t\t.map((item) => item.dueAt - nowMs)\n\t\t\t\t.sort((left, right) => left - right);\n\t\t},\n\t\tasync advanceBy(delayMs) {\n\t\t\tconst target = nowMs + delayMs;\n\t\t\twhile (true) {\n\t\t\t\tconst next = [...scheduled.values()]\n\t\t\t\t\t.filter((item) => item.dueAt <= target)\n\t\t\t\t\t.sort((left, right) => left.dueAt - right.dueAt || left.id - right.id)[0];\n\t\t\t\tif (!next) break;\n\t\t\t\tnowMs = next.dueAt;\n\t\t\t\tscheduled.delete(next.id);\n\t\t\t\tnext.handler();\n\t\t\t\tawait Promise.resolve();\n\t\t\t}\n\t\t\tnowMs = target;\n\t\t},\n\t};\n}\n\nexport interface WorkerRuntimeHarnessOptions {\n\tconfig?: Partial<WorkerRuntimeConfig>;\n\t/** Optional default used by start() and startLlmTo(). */\n\tstartPayload?: WorkerStartPayload;\n\tadapters: Pick<WorkerRuntimeAdapters, \"piFactory\" | \"gitOps\"> &\n\t\tPartial<\n\t\t\tPick<\n\t\t\t\tWorkerRuntimeAdapters,\n\t\t\t\t| \"sessionSnapshots\"\n\t\t\t\t| \"resultImageTools\"\n\t\t\t\t| \"sampleCredentials\"\n\t\t\t\t| \"resolveWorkerProcess\"\n\t\t\t\t| \"stderr\"\n\t\t\t\t| \"extensionEvents\"\n\t\t\t>\n\t\t>;\n}\n\nexport type WorkerRuntimeObservation =\n\t| { kind: \"ipc\"; type: WorkerToServerMessage[\"type\"] }\n\t| { kind: \"extension\"; event: string };\n\nexport function createWorkerRuntimeHarness(options: WorkerRuntimeHarnessOptions) {\n\tlet messageHandler: ((message: ServerToWorkerMessage) => void) | undefined;\n\tlet errorHandler: ((error: Error) => void) | undefined;\n\tlet connectHandler: (() => void) | undefined;\n\tconst outgoing: WorkerToServerMessage[] = [];\n\tconst waiters = new Set<MessageWaiter>();\n\tconst messagesOfType = <T extends WorkerMessageType>(type: T): WorkerMessageByType<T>[] =>\n\t\toutgoing.filter((message) => message.type === type) as WorkerMessageByType<T>[];\n\tconst notifyWaiters = (): void => {\n\t\tfor (const waiter of waiters) {\n\t\t\tconst matches = messagesOfType(waiter.type);\n\t\t\tconst message = matches[waiter.count - 1];\n\t\t\tif (!message) continue;\n\t\t\twaiters.delete(waiter);\n\t\t\twaiter.resolve(message);\n\t\t}\n\t};\n\tconst observations: WorkerRuntimeObservation[] = [];\n\tconst exitCodes: number[] = [];\n\tlet transportStartCount = 0;\n\tlet transportStopCount = 0;\n\tlet nextMessageId = 1;\n\tlet latestStart: WorkerStartPayload | undefined;\n\tconst instanceId = options.config?.instanceId ?? \"proc_test\";\n\tconst workerId = options.config?.workerId ?? \"worker_test\";\n\tconst deliver = <T extends ServerMessageType>(\n\t\ttype: T,\n\t\tpayload: ServerMessagePayloadByType[T],\n\t): void => {\n\t\tif (type === \"worker.start\") latestStart = payload as WorkerStartPayload;\n\t\tmessageHandler?.(\n\t\t\tcreateIpcMessage({\n\t\t\t\ttype,\n\t\t\t\tpayload,\n\t\t\t\tmessageId: `harness_${nextMessageId++}`,\n\t\t\t\tinstanceId,\n\t\t\t\tworkerId,\n\t\t\t} as never) as ServerToWorkerMessage,\n\t\t);\n\t};\n\tconst scheduler = createManualWorkerRuntimeScheduler();\n\tconst transport: WorkerRuntimeAdapters[\"transport\"] = {\n\t\tsend(message) {\n\t\t\toutgoing.push(message);\n\t\t\tobservations.push({ kind: \"ipc\", type: message.type });\n\t\t\tnotifyWaiters();\n\t\t},\n\t\tonMessage(handler) {\n\t\t\tmessageHandler = handler;\n\t\t},\n\t\tonError(handler) {\n\t\t\terrorHandler = handler;\n\t\t},\n\t\tonConnect(handler) {\n\t\t\tconnectHandler = handler;\n\t\t},\n\t\tstart() {\n\t\t\ttransportStartCount++;\n\t\t},\n\t\tstop() {\n\t\t\ttransportStopCount++;\n\t\t},\n\t};\n\tconst delegatedExtensionEvents = options.adapters.extensionEvents ?? createEventBus();\n\tconst extensionEvents: NonNullable<WorkerRuntimeAdapters[\"extensionEvents\"]> = {\n\t\temit(event, payload) {\n\t\t\tobservations.push({ kind: \"extension\", event });\n\t\t\tdelegatedExtensionEvents.emit(event, payload);\n\t\t},\n\t\ton(event, handler) {\n\t\t\tdelegatedExtensionEvents.on(event, handler);\n\t\t},\n\t\toff(event, handler) {\n\t\t\tdelegatedExtensionEvents.off(event, handler);\n\t\t},\n\t};\n\tconst runtime = createWorkerRuntime({\n\t\tconfig: {\n\t\t\tinstanceId,\n\t\t\tworkerId,\n\t\t\theartbeatIntervalMs: options.config?.heartbeatIntervalMs,\n\t\t\tturnMaxDurationMs: options.config?.turnMaxDurationMs,\n\t\t\tturnInactivityTimeoutMs: options.config?.turnInactivityTimeoutMs,\n\t\t\tturnAbortGracePeriodMs: options.config?.turnAbortGracePeriodMs,\n\t\t},\n\t\tadapters: {\n\t\t\ttransport,\n\t\t\tscheduler,\n\t\t\tresultImageTools: options.adapters.resultImageTools ?? { create: () => null },\n\t\t\tpiFactory: options.adapters.piFactory,\n\t\t\tgitOps: options.adapters.gitOps,\n\t\t\tsampleCredentials: options.adapters.sampleCredentials,\n\t\t\tresolveWorkerProcess: options.adapters.resolveWorkerProcess,\n\t\t\tstderr: options.adapters.stderr,\n\t\t\textensionEvents,\n\t\t\tsessionSnapshots:\n\t\t\t\toptions.adapters.sessionSnapshots ??\n\t\t\t\t({\n\t\t\t\t\tasync uploadSnapshot() {\n\t\t\t\t\t\treturn { kind: \"uploaded\", bytes: 0 } as const;\n\t\t\t\t\t},\n\t\t\t\t} satisfies WorkerRuntimeAdapters[\"sessionSnapshots\"]),\n\t\t\texit(code) {\n\t\t\t\texitCodes.push(code);\n\t\t\t},\n\t\t},\n\t});\n\n\treturn {\n\t\tscheduler,\n\t\toutgoing,\n\t\tobservations,\n\t\texitCodes,\n\t\tget transportStartCount() {\n\t\t\treturn transportStartCount;\n\t\t},\n\t\tget transportStopCount() {\n\t\t\treturn transportStopCount;\n\t\t},\n\t\tdeliver,\n\t\tasync connect() {\n\t\t\tawait runtime.start();\n\t\t},\n\t\tasync start(payload = options.startPayload) {\n\t\t\tif (!payload) throw new Error(\"WorkerRuntimeHarness.start requires a start payload\");\n\t\t\tawait this.connect();\n\t\t\tdeliver(\"worker.start\", payload);\n\t\t\tawait this.flush();\n\t\t},\n\t\tasync stop(reason: string) {\n\t\t\tawait runtime.stop(reason);\n\t\t},\n\t\tasync acceptStart(acceptance: { startRecordId?: string; turnRecordId?: string } = {}) {\n\t\t\tif (!latestStart) throw new Error(\"Cannot accept a turn before worker.start\");\n\t\t\tdeliver(\"worker.turn_start_accepted\", {\n\t\t\t\tstartRecordId: acceptance.startRecordId ?? latestStart.turnStart.id,\n\t\t\t\tturnRecordId: acceptance.turnRecordId ?? latestStart.turnStart.proposedTurnRecordId,\n\t\t\t});\n\t\t\tawait this.flush();\n\t\t},\n\t\tasync startLlmTo<T extends WorkerMessageType>(\n\t\t\ttype: T,\n\t\t\tpayload = options.startPayload,\n\t\t): Promise<WorkerMessageByType<T>> {\n\t\t\tif (!payload) throw new Error(\"WorkerRuntimeHarness.startLlmTo requires a start payload\");\n\t\t\tif (payload.bootstrap.kind !== \"llm\") {\n\t\t\t\tthrow new Error(\"WorkerRuntimeHarness.startLlmTo requires an LLM start payload\");\n\t\t\t}\n\t\t\tawait this.start(payload);\n\t\t\tawait this.waitForMessage(\"worker.ready\");\n\t\t\tawait this.acceptStart();\n\t\t\treturn this.waitForMessage(type);\n\t\t},\n\t\treconnect() {\n\t\t\tconnectHandler?.();\n\t\t},\n\t\tfailTransport(error: Error) {\n\t\t\terrorHandler?.(error);\n\t\t},\n\t\tasync waitForMessage<T extends WorkerMessageType>(\n\t\t\ttype: T,\n\t\t\tcount = 1,\n\t\t): Promise<WorkerMessageByType<T>> {\n\t\t\tconst matches = messagesOfType(type);\n\t\t\tif (matches.length >= count) return matches[count - 1] as (typeof matches)[number];\n\t\t\treturn new Promise<(typeof matches)[number]>((resolve) =>\n\t\t\t\twaiters.add({\n\t\t\t\t\ttype,\n\t\t\t\t\tcount,\n\t\t\t\t\tresolve: (message) => resolve(message as (typeof matches)[number]),\n\t\t\t\t}),\n\t\t\t);\n\t\t},\n\t\tasync flush() {\n\t\t\tfor (let index = 0; index < 100; index++)\n\t\t\t\tawait new Promise<void>((resolve) => setImmediate(resolve));\n\t\t},\n\t};\n}\n\nexport type WorkerRuntimeHarness = ReturnType<typeof createWorkerRuntimeHarness>;\n","import path from \"node:path\";\nimport { VERSION as PI_VERSION } from \"@earendil-works/pi-coding-agent\";\nimport type { ResolvedTurnStart } from \"@leitwerk-dev/domain\";\nimport {\n\tcreateCanonicalPiResourceBundle,\n\tcreateTestConfigSnapshot,\n\ttype InputDelivery,\n\ttype ProcessInstanceSnapshot,\n\ttype ProcessProjectSnapshot,\n\tsha256Digest,\n\tWORKER_API_VERSION,\n\ttype WorkerCredentialMaterial,\n\ttype WorkerStartPayload,\n} from \"@leitwerk-dev/worker-protocol\";\n\ntype LlmStart = Extract<ResolvedTurnStart, { kind: \"llm\" }>;\ntype LlmModel = LlmStart[\"model\"];\n\nexport interface TestLlmWorkerStartPayloadOptions {\n\troot: string;\n\tprocessSnapshot: ProcessInstanceSnapshot;\n\tprojectSnapshots?: ProcessProjectSnapshot[];\n\tturnResultMarkdownBySemanticRef?: WorkerStartPayload[\"turnResultMarkdownBySemanticRef\"];\n\tturnResultMarkdownByProduct?: WorkerStartPayload[\"turnResultMarkdownByProduct\"];\n\tpendingInputs?: InputDelivery[];\n\tworkerLeaseId?: string;\n\tstartRecordId?: string;\n\tturnRecordId?: string;\n\tmodel?: LlmModel;\n\tcredential?: WorkerCredentialMaterial | null;\n\tresume?: boolean;\n\tnow?: string;\n}\n\n/** Builds a valid public LLM worker.start payload with canonical Pi resources. */\nexport function createTestLlmWorkerStartPayload(\n\toptions: TestLlmWorkerStartPayloadOptions,\n): WorkerStartPayload {\n\tconst instanceId = options.processSnapshot.id ?? \"proc_test\";\n\tconst model =\n\t\toptions.model ??\n\t\t({\n\t\t\tprofileId: \"test\",\n\t\t\tproviderId: \"openai\",\n\t\t\tmodelId: \"test-model\",\n\t\t\tthinkingLevel: \"low\",\n\t\t} satisfies LlmModel);\n\tconst immutableFiles = [\n\t\t{\n\t\t\tpath: \"settings.json\",\n\t\t\tcontent: Buffer.from('{\"defaultProjectTrust\":\"never\",\"packages\":[]}\\n'),\n\t\t},\n\t\t{ path: \"models.json\", content: Buffer.from('{\"providers\":{}}\\n') },\n\t];\n\tconst generated = {\n\t\tschemaVersion: 1,\n\t\tmodel,\n\t\tproviderOptions: {},\n\t\tproviderWorkerConfig: null,\n\t\tdeclaredCredentialPaths: [\"auth.json\"],\n\t\tcompatibility: { workerApiVersion: WORKER_API_VERSION, piVersion: PI_VERSION },\n\t\tprovenance: immutableFiles.map((file) => ({\n\t\t\tkind: \"generated\" as const,\n\t\t\townerExtensionId: null,\n\t\t\tpackageName: null,\n\t\t\tsnapshotPath: file.path,\n\t\t\tsha256: sha256Digest(file.content),\n\t\t\tsize: file.content.byteLength,\n\t\t})),\n\t};\n\tconst bundle = createCanonicalPiResourceBundle([\n\t\t...immutableFiles,\n\t\t{ path: \"generated.json\", content: Buffer.from(`${JSON.stringify(generated)}\\n`) },\n\t]);\n\tconst configSnapshot = createTestConfigSnapshot();\n\tconfigSnapshot.pi.agent_dir = path.join(options.root, \"agent\");\n\tconfigSnapshot.pi.model_profiles = [\n\t\t{\n\t\t\tid: model.profileId,\n\t\t\tprovider: model.providerId,\n\t\t\tmodel_id: model.modelId,\n\t\t\tthinking_level: model.thinkingLevel,\n\t\t},\n\t];\n\tconst now = options.now ?? \"2025-01-01T00:00:00.000Z\";\n\treturn {\n\t\tprocessSnapshot: options.processSnapshot,\n\t\tprojectSnapshots: options.projectSnapshots ?? [],\n\t\tturnResultMarkdownBySemanticRef: options.turnResultMarkdownBySemanticRef,\n\t\tturnResultMarkdownByProduct: options.turnResultMarkdownByProduct,\n\t\tworkerLeaseId: options.workerLeaseId ?? \"lease_1\",\n\t\tturnStart: {\n\t\t\tid: options.startRecordId ?? \"start_1\",\n\t\t\tinstanceId,\n\t\t\tturnId: options.processSnapshot.selectedTurnId ?? \"run\",\n\t\t\tturnType: \"llm\",\n\t\t\tproposedTurnRecordId: options.turnRecordId ?? \"trn_1\",\n\t\t\tstartKind: \"selected_turn\",\n\t\t\trecoveryTurnRecordId: null,\n\t\t\tcontinuation: null,\n\t\t\tstate: {\n\t\t\t\tkind: \"starting\",\n\t\t\t\tstart: {\n\t\t\t\t\tkind: \"llm\",\n\t\t\t\t\tmodel,\n\t\t\t\t\tproviderOptions: {},\n\t\t\t\t\tproviderWorkerConfig: null,\n\t\t\t\t\tpiResourceSnapshotDigest: bundle.digest,\n\t\t\t\t\tworkerRuntimeProfileId: \"default\",\n\t\t\t\t\tpiSettings: {},\n\t\t\t\t},\n\t\t\t},\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now,\n\t\t},\n\t\tpendingInputs: options.pendingInputs ?? [],\n\t\tbootstrap: {\n\t\t\tkind: \"llm\",\n\t\t\tresourceBundle: {\n\t\t\t\tdigest: bundle.digest,\n\t\t\t\tarchiveBase64: Buffer.from(bundle.bytes).toString(\"base64\"),\n\t\t\t},\n\t\t\tcredential:\n\t\t\t\toptions.credential === undefined\n\t\t\t\t\t? { providerId: model.providerId, revision: 1, values: { apiKey: \"test-secret\" } }\n\t\t\t\t\t: options.credential,\n\t\t},\n\t\tconfigSnapshot,\n\t\ttreePaths: {\n\t\t\tprimaryTreeFile: path.join(options.root, \"tree\", \"primary.jsonl\"),\n\t\t\tworkspaceRoot: path.join(options.root, \"workspace\"),\n\t\t},\n\t\tresume: options.resume ?? false,\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA,SAAS,sBAAsB;AAC/B;AAAA,EACC;AAAA,OAIM;AACP;AAAA,EACC;AAAA,OAIM;AA0BA,SAAS,mCACf,aAAa,oBAAI,KAAK,0BAA0B,GACjB;AAC/B,MAAI,QAAQ,WAAW,QAAQ;AAC/B,MAAI,SAAS;AACb,QAAM,YAAY,oBAAI,IAAuB;AAC7C,QAAM,UAAU,CAAC,OAAe;AAChC,QAAM,YAAY,CAAC,UAAiB;AAEpC,QAAM,WAAW,CAAC,SAAqB,YAA4B;AAClE,UAAM,KAAK;AACX,cAAU,IAAI,IAAI,EAAE,IAAI,OAAO,QAAQ,SAAS,QAAQ,CAAC;AACzD,WAAO;AAAA,EACR;AACA,QAAM,aAAa,CAAC,UAAuB;AAC1C,cAAU,OAAO,UAAU,KAAK,CAAC;AAAA,EAClC;AAEA,SAAO;AAAA,IACN,YAAY,CAAC,SAAS,YAAY,QAAQ,SAAS,SAAS,OAAO,CAAC;AAAA,IACpE,cAAc;AAAA,IACd,OAAO,CAAC,YAAY,IAAI,QAAQ,CAAC,YAAY,SAAS,SAAS,OAAO,CAAC;AAAA,IACvE,MAAM;AACL,aAAO,IAAI,KAAK,KAAK;AAAA,IACtB;AAAA,IACA,gBAAgB;AACf,aAAO,CAAC,GAAG,UAAU,OAAO,CAAC,EAC3B,IAAI,CAAC,SAAS,KAAK,QAAQ,KAAK,EAChC,KAAK,CAAC,MAAM,UAAU,OAAO,KAAK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wB;AAAA,UACxB,YAAY,CAAC;AAAA,QACd;AAAA,MACD;AAAA,MACA,WAAW;AAAA,MACX,WAAW;AAAA,IACZ;AAAA,IACA,eAAe,QAAQ,iBAAiB,CAAC;AAAA,IACzC,WAAW;AAAA,MACV,MAAM;AAAA,MACN,gBAAgB;AAAA,QACf,QAAQ,OAAO;AAAA,QACf,eAAe,OAAO,KAAK,OAAO,KAAK,EAAE,SAAS,QAAQ;AAAA,MAC3D;AAAA,MACA,YACC,QAAQ,eAAe,SACpB,EAAE,YAAY,MAAM,YAAY,UAAU,GAAG,QAAQ,EAAE,QAAQ,cAAc,EAAE,IAC/E,QAAQ;AAAA,IACb;AAAA,IACA;AAAA,IACA,WAAW;AAAA,MACV,iBAAiB,KAAK,KAAK,QAAQ,MAAM,QAAQ,eAAe;AAAA,MAChE,eAAe,KAAK,KAAK,QAAQ,MAAM,WAAW;AAAA,IACnD;AAAA,IACA,QAAQ,QAAQ,UAAU;AAAA,EAC3B;AACD;","names":[]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/worker-testing/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,0BAA0B,GAE1B,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AACpF,OAAO,EACN,+BAA+B,EAC/B,wCAAwC,EACxC,sBAAsB,EACtB,sBAAsB,GACtB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACN,8BAA8B,GAE9B,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACN,gBAAgB,EAChB,uBAAuB,GAMvB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACN,kCAAkC,EAClC,0BAA0B,GAK1B,MAAM,6BAA6B,CAAC;AACrC,OAAO,EACN,+BAA+B,GAE/B,MAAM,2BAA2B,CAAC"}
@@ -0,0 +1,17 @@
1
+ import { createTestConfigSnapshot, IPC_PROTOCOL_VERSION } from "@leitwerk-dev/worker-protocol";
2
+ export async function flushAsyncWork(iterations = 30) {
3
+ for (let i = 0; i < iterations; i++) {
4
+ await new Promise((resolve) => setImmediate(resolve));
5
+ }
6
+ }
7
+ export const testConfigSnapshot = createTestConfigSnapshot;
8
+ export function baseEnvelope(instanceId, workerId, messageId) {
9
+ return {
10
+ protocol: IPC_PROTOCOL_VERSION,
11
+ messageId,
12
+ instanceId,
13
+ workerId,
14
+ sentAt: new Date().toISOString(),
15
+ };
16
+ }
17
+ //# sourceMappingURL=ipc-harness.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ipc-harness.js","sourceRoot":"","sources":["../../src/worker-testing/ipc-harness.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AAE/F,MAAM,CAAC,KAAK,UAAU,cAAc,CAAC,UAAU,GAAG,EAAE;IACnD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,UAAU,EAAE,CAAC,EAAE,EAAE,CAAC;QACrC,MAAM,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC,CAAC;IAC7D,CAAC;AACF,CAAC;AAED,MAAM,CAAC,MAAM,kBAAkB,GAAG,wBAAwB,CAAC;AAE3D,MAAM,UAAU,YAAY,CAAC,UAAkB,EAAE,QAAgB,EAAE,SAAiB;IACnF,OAAO;QACN,QAAQ,EAAE,oBAAmD;QAC7D,SAAS;QACT,UAAU;QACV,QAAQ;QACR,MAAM,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;KAChC,CAAC;AACH,CAAC"}
@@ -0,0 +1,65 @@
1
+ import { StubPiTreeHandleFactory, } from "./stub-pi-tree-handle.js";
2
+ function isObjectLike(value) {
3
+ return typeof value === "object" && value !== null;
4
+ }
5
+ export function synthesizeStubArgValue(key, spec) {
6
+ if (key === "changedProjects") {
7
+ return undefined;
8
+ }
9
+ const type = isObjectLike(spec) && typeof spec.type === "string" ? spec.type : "string";
10
+ switch (type) {
11
+ case "number":
12
+ case "integer":
13
+ return 1;
14
+ case "boolean":
15
+ return true;
16
+ case "array": {
17
+ const itemSpec = isObjectLike(spec) ? spec.items : undefined;
18
+ return [synthesizeStubArgValue(`${key}_item`, itemSpec)];
19
+ }
20
+ case "object":
21
+ return {};
22
+ default:
23
+ return `${key} value`;
24
+ }
25
+ }
26
+ export function synthesizeStubToolArgs(parameters) {
27
+ const parameterEntries = isObjectLike(parameters) && parameters.type === "object" && isObjectLike(parameters.properties)
28
+ ? Object.entries(parameters.properties)
29
+ : Object.entries(parameters);
30
+ return Object.fromEntries(parameterEntries.map(([key, spec]) => [key, synthesizeStubArgValue(key, spec)]));
31
+ }
32
+ export function createSchemaDrivenToolCallScriptResolver() {
33
+ return ({ tools }) => {
34
+ const markdownTool = tools.find((tool) => tool.name === "markdown_result");
35
+ const completionTool = tools.find((tool) => tool.name !== "markdown_result" && tool.name !== "upload_result_images");
36
+ if (markdownTool && completionTool) {
37
+ return {
38
+ calls: [
39
+ {
40
+ toolName: markdownTool.name,
41
+ args: synthesizeStubToolArgs(markdownTool.parameters),
42
+ },
43
+ {
44
+ toolName: completionTool.name,
45
+ args: synthesizeStubToolArgs(completionTool.parameters),
46
+ },
47
+ ],
48
+ };
49
+ }
50
+ const tool = markdownTool ?? completionTool ?? tools[0];
51
+ if (!tool) {
52
+ return undefined;
53
+ }
54
+ return {
55
+ toolName: tool.name,
56
+ args: synthesizeStubToolArgs(tool.parameters),
57
+ };
58
+ };
59
+ }
60
+ export function createSchemaDrivenStubPiFactory(options = {}) {
61
+ return new StubPiTreeHandleFactory({
62
+ toolCallScriptResolver: options.toolCallScriptResolver ?? createSchemaDrivenToolCallScriptResolver(),
63
+ });
64
+ }
65
+ //# sourceMappingURL=schema-driven-stub-pi.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema-driven-stub-pi.js","sourceRoot":"","sources":["../../src/worker-testing/schema-dri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+B,CAC9C,UAAmE,EAAE;IAErE,OAAO,IAAI,uBAAuB,CAAC;QAClC,sBAAsB,EACrB,OAAO,CAAC,sBAAsB,IAAI,wCAAwC,EAAE;KAC7E,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,10 @@
1
+ export function createStubToolScriptController() {
2
+ const queue = [];
3
+ return {
4
+ resolver: () => queue.shift(),
5
+ set(script) {
6
+ queue.splice(0, queue.length, ...script);
7
+ },
8
+ };
9
+ }
10
+ //# sourceMappingURL=stub-pi-controls.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stub-pi-controls.js","sourceRoot":"","sources":["../../src/worker-testing/stub-pi-controls.ts"],"names":[],"mappings":"AAOA,MAAM,UAAU,8BAA8B;IAC7C,MAAM,KAAK,GAA6B,EAAE,CAAC;IAC3C,OAAO;QACN,QAAQ,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,KAAK,EAAE;QAC7B,GAAG,CAAC,MAAM;YACT,KAAK,CAAC,MAAM,CAAC,CAAC,EAAE,KAAK,CAAC,MAAM,EAAE,GAAG,MAAM,CAAC,CAAC;QAC1C,CAAC;KACD,CAAC;AACH,CAAC"}
@@ -0,0 +1,515 @@
1
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ function stringifyToolResult(result) {
4
+ if (typeof result === "string") {
5
+ return result;
6
+ }
7
+ if (result === undefined) {
8
+ return "ok";
9
+ }
10
+ try {
11
+ return JSON.stringify(result, null, 2);
12
+ }
13
+ catch {
14
+ return String(result);
15
+ }
16
+ }
17
+ function expandStubToolCallScriptItem(item) {
18
+ if ("calls" in item) {
19
+ return [...item.calls];
20
+ }
21
+ return [item];
22
+ }
23
+ function stubToolCallId(turnSeq, totalCalls, index) {
24
+ if (totalCalls <= 1) {
25
+ return `tool-${turnSeq}`;
26
+ }
27
+ return `tool-${turnSeq}-${index + 1}`;
28
+ }
29
+ function createEmptyStubPiTreeState() {
30
+ return {
31
+ turnSeq: 0,
32
+ currentLeafId: null,
33
+ entries: new Map(),
34
+ childIdsByParent: new Map(),
35
+ };
36
+ }
37
+ function deriveStubLeafIdFromEntries(state) {
38
+ let leafId = null;
39
+ for (const entryId of state.entries.keys()) {
40
+ leafId = entryId;
41
+ }
42
+ return leafId;
43
+ }
44
+ function serializeStubPiTreeState(state) {
45
+ const persisted = {
46
+ turnSeq: state.turnSeq,
47
+ currentLeafId: state.currentLeafId,
48
+ entries: [...state.entries.values()],
49
+ childIdsByParent: [...state.childIdsByParent.entries()].map(([parentId, childIds]) => ({
50
+ parentId,
51
+ childIds: [...childIds],
52
+ })),
53
+ };
54
+ return JSON.stringify(persisted);
55
+ }
56
+ function deserializeStubPiTreeState(value) {
57
+ const parsed = JSON.parse(value);
58
+ return {
59
+ turnSeq: typeof parsed.turnSeq === "number" ? parsed.turnSeq : 0,
60
+ currentLeafId: typeof parsed.currentLeafId === "string" || parsed.currentLeafId === null
61
+ ? parsed.currentLeafId
62
+ : null,
63
+ entries: new Map((parsed.entries ?? []).map((entry) => [entry.id, entry])),
64
+ childIdsByParent: new Map((parsed.childIdsByParent ?? []).map((entry) => [entry.parentId, [...entry.childIds]])),
65
+ };
66
+ }
67
+ export class StubPiTreeHandle {
68
+ sessionId;
69
+ treeFile;
70
+ isResumed;
71
+ prompts = [];
72
+ steers = [];
73
+ beforeTurn;
74
+ _closed = false;
75
+ branchDriftPending = false;
76
+ handlers = new Set();
77
+ diagnosticHandlers = new Set();
78
+ toolCallScriptResolver;
79
+ state;
80
+ runDetails;
81
+ persistState;
82
+ constructor(options) {
83
+ this.sessionId = options.sessionId;
84
+ this.treeFile = options.treeFile;
85
+ this.isResumed = options.isResumed;
86
+ this.toolCallScriptResolver = options.toolCallScriptResolver;
87
+ this.state = options.state ?? createEmptyStubPiTreeState();
88
+ this.persistState = options.persistState;
89
+ this.runDetails = {
90
+ loadedAgentsFiles: options.runDetails?.loadedAgentsFiles?.map((file) => ({ ...file })) ?? [],
91
+ loadedSkills: options.runDetails?.loadedSkills?.map((skill) => ({ ...skill })) ?? [],
92
+ availableToolNames: [...(options.runDetails?.availableToolNames ?? [])],
93
+ };
94
+ }
95
+ get closed() {
96
+ return this._closed;
97
+ }
98
+ failNextTurnWithBranchDrift() {
99
+ this.branchDriftPending = true;
100
+ }
101
+ assertOpen() {
102
+ if (this._closed) {
103
+ throw new Error("Handle is closed");
104
+ }
105
+ }
106
+ addEntry(entry) {
107
+ this.state.entries.set(entry.id, entry);
108
+ const siblings = this.state.childIdsByParent.get(entry.parentId) ?? [];
109
+ siblings.push(entry.id);
110
+ this.state.childIdsByParent.set(entry.parentId, siblings);
111
+ this.state.currentLeafId = entry.id;
112
+ }
113
+ createMessageEntry(id, parentId, role, content, timestamp) {
114
+ return {
115
+ id,
116
+ parentId,
117
+ type: "message",
118
+ timestamp,
119
+ message: {
120
+ role,
121
+ content,
122
+ },
123
+ };
124
+ }
125
+ emitEvent(event) {
126
+ for (const handler of this.handlers) {
127
+ handler(event);
128
+ }
129
+ }
130
+ getRunDetails() {
131
+ return {
132
+ loadedAgentsFiles: this.runDetails.loadedAgentsFiles.map((file) => ({ ...file })),
133
+ loadedSkills: this.runDetails.loadedSkills.map((skill) => ({ ...skill })),
134
+ availableToolNames: [...this.runDetails.availableToolNames],
135
+ };
136
+ }
137
+ getLeafId() {
138
+ return this.state.currentLeafId;
139
+ }
140
+ getEntry(id) {
141
+ return this.state.entries.get(id);
142
+ }
143
+ getBranch(fromId = this.state.currentLeafId ?? undefined) {
144
+ if (!fromId) {
145
+ return [];
146
+ }
147
+ const branch = [];
148
+ let currentId = fromId;
149
+ while (currentId) {
150
+ const entry = this.state.entries.get(currentId);
151
+ if (!entry) {
152
+ break;
153
+ }
154
+ branch.push(entry);
155
+ currentId = entry.parentId;
156
+ }
157
+ branch.reverse();
158
+ return branch;
159
+ }
160
+ getChildren(parentId) {
161
+ return (this.state.childIdsByParent.get(parentId) ?? [])
162
+ .map((childId) => this.state.entries.get(childId))
163
+ .filter((entry) => entry !== undefined);
164
+ }
165
+ getTree() {
166
+ const buildNode = (entry) => ({
167
+ entry,
168
+ children: this.getChildren(entry.id).map(buildNode),
169
+ });
170
+ return (this.state.childIdsByParent.get(null) ?? [])
171
+ .map((entryId) => this.state.entries.get(entryId))
172
+ .filter((entry) => entry !== undefined)
173
+ .map(buildNode);
174
+ }
175
+ async branch(entryId) {
176
+ this.assertOpen();
177
+ if (!this.state.entries.has(entryId)) {
178
+ throw new Error(`Unknown Pi entry '${entryId}'`);
179
+ }
180
+ this.state.currentLeafId = entryId;
181
+ await this.persistState?.();
182
+ }
183
+ async branchFromRoot() {
184
+ this.assertOpen();
185
+ this.state.currentLeafId = null;
186
+ await this.persistState?.();
187
+ }
188
+ async resetLeaf() {
189
+ await this.branchFromRoot();
190
+ }
191
+ async compact(_customInstructions, details) {
192
+ this.assertOpen();
193
+ const timestamp = new Date().toISOString();
194
+ const compactionEntryId = `compaction-${++this.state.turnSeq}`;
195
+ this.addEntry({
196
+ id: compactionEntryId,
197
+ parentId: this.state.currentLeafId,
198
+ type: "compaction",
199
+ timestamp,
200
+ details,
201
+ });
202
+ await this.persistState?.();
203
+ return { summary: "Stub compaction" };
204
+ }
205
+ async executeTurn(input) {
206
+ this.assertOpen();
207
+ if ((await this.beforeTurn?.(input.kind, input.options, input.promptText)) === false) {
208
+ input.options = undefined;
209
+ }
210
+ if (this.branchDriftPending) {
211
+ this.branchDriftPending = false;
212
+ throw Object.assign(new Error("stubbed Pi branch drift"), {
213
+ name: "PiBranchDriftError",
214
+ failureCode: "branch_drift",
215
+ toTurnFailureOptions: () => ({
216
+ failureCode: "branch_drift",
217
+ failureDetails: { operation: input.kind },
218
+ recoveryContext: null,
219
+ restorePrimaryLeaf: false,
220
+ }),
221
+ });
222
+ }
223
+ if (input.promptText !== undefined) {
224
+ this.prompts.push(input.promptText);
225
+ }
226
+ const startLeafId = this.state.currentLeafId;
227
+ const turnId = `turn-${++this.state.turnSeq}`;
228
+ const timestamp = new Date().toISOString();
229
+ const createdEntryIds = [];
230
+ if (input.appendPromptUserMessage) {
231
+ const userEntryId = `user-${this.state.turnSeq}`;
232
+ this.addEntry(this.createMessageEntry(userEntryId, this.state.currentLeafId, "user", input.promptText ?? "", timestamp));
233
+ createdEntryIds.push(userEntryId);
234
+ }
235
+ this.emitEvent({ type: "turn.start", turnId, data: {}, timestamp });
236
+ const tools = new Map((input.options?.tools ?? []).map((tool) => [tool.name, tool]));
237
+ let assistantContent = input.promptText ?? "Continued.";
238
+ let assistantContentFromScriptedMarkdown = false;
239
+ const scriptedItem = this.toolCallScriptResolver?.({
240
+ promptText: input.promptText ?? "",
241
+ tools: input.options?.tools ?? [],
242
+ });
243
+ const scriptedCalls = scriptedItem ? expandStubToolCallScriptItem(scriptedItem) : [];
244
+ if (scriptedCalls.length > 0) {
245
+ for (const [callIndex, scriptedCall] of scriptedCalls.entries()) {
246
+ const toolCallId = stubToolCallId(this.state.turnSeq, scriptedCalls.length, callIndex);
247
+ this.emitEvent({
248
+ type: "tool.call",
249
+ turnId,
250
+ data: {
251
+ toolCallId,
252
+ name: scriptedCall.toolName,
253
+ arguments: scriptedCall.args,
254
+ },
255
+ timestamp,
256
+ });
257
+ const tool = tools.get(scriptedCall.toolName);
258
+ if (!tool && scriptedCall.toolName === "markdown_result") {
259
+ const markdown = scriptedCall.args.markdown;
260
+ if (typeof markdown === "string") {
261
+ assistantContent = markdown;
262
+ assistantContentFromScriptedMarkdown = true;
263
+ }
264
+ }
265
+ if (tool) {
266
+ try {
267
+ const result = await tool.execute(scriptedCall.args);
268
+ if (!assistantContentFromScriptedMarkdown) {
269
+ assistantContent = stringifyToolResult(result);
270
+ }
271
+ this.emitEvent({
272
+ type: "tool.result",
273
+ turnId,
274
+ data: { toolCallId, name: scriptedCall.toolName, result },
275
+ timestamp,
276
+ });
277
+ }
278
+ catch (error) {
279
+ this.emitEvent({
280
+ type: "error",
281
+ turnId,
282
+ data: {
283
+ message: error instanceof Error ? error.message : String(error),
284
+ toolName: scriptedCall.toolName,
285
+ },
286
+ timestamp,
287
+ });
288
+ throw error;
289
+ }
290
+ }
291
+ for (let i = 0; i < (scriptedCall.intermediateEntryCount ?? 0); i++) {
292
+ const intermediateEntryId = scriptedCalls.length === 1
293
+ ? `intermediate-${this.state.turnSeq}-${i + 1}`
294
+ : `intermediate-${this.state.turnSeq}-${callIndex + 1}-${i + 1}`;
295
+ this.addEntry(this.createMessageEntry(intermediateEntryId, this.state.currentLeafId, "assistant", `Intermediate entry ${i + 1}`, timestamp));
296
+ createdEntryIds.push(intermediateEntryId);
297
+ }
298
+ }
299
+ }
300
+ else if (tools.size > 0) {
301
+ throw new Error(`Stub Pi prompt requires a stub tool-call script when tools are provided (${[...tools.keys()].join(", ")})`);
302
+ }
303
+ else if (input.promptText !== undefined) {
304
+ this.emitEvent({
305
+ type: "stream.delta",
306
+ turnId,
307
+ data: { text: input.promptText },
308
+ timestamp,
309
+ });
310
+ }
311
+ this.addEntry(this.createMessageEntry(turnId, this.state.currentLeafId, "assistant", assistantContent, timestamp));
312
+ createdEntryIds.push(turnId);
313
+ await this.persistState?.();
314
+ this.emitEvent({ type: "turn.end", turnId, data: {}, timestamp });
315
+ const resultEntryId = this.state.currentLeafId;
316
+ if (!resultEntryId) {
317
+ throw new Error(input.appendPromptUserMessage
318
+ ? "Stub Pi prompt completed without an active leaf"
319
+ : "Stub Pi continuation completed without an active leaf");
320
+ }
321
+ return {
322
+ startLeafId,
323
+ endLeafId: resultEntryId,
324
+ createdEntryIds,
325
+ resultEntryId,
326
+ assistantMarkdown: assistantContent,
327
+ };
328
+ }
329
+ async prompt(text, options = {}) {
330
+ return await this.executeTurn({
331
+ kind: "prompt",
332
+ promptText: text,
333
+ options,
334
+ appendPromptUserMessage: true,
335
+ });
336
+ }
337
+ async promptLiteral(text, options = {}) {
338
+ return await this.executeTurn({
339
+ kind: "literal",
340
+ promptText: text,
341
+ options,
342
+ appendPromptUserMessage: true,
343
+ });
344
+ }
345
+ async promptCustom(input, options = {}) {
346
+ const startLeafId = this.getLeafId();
347
+ const promptEntryId = await this.appendCustomMessage(input);
348
+ const result = await this.executeTurn({
349
+ kind: "custom",
350
+ options,
351
+ appendPromptUserMessage: false,
352
+ });
353
+ return {
354
+ ...result,
355
+ startLeafId,
356
+ createdEntryIds: [promptEntryId, ...result.createdEntryIds],
357
+ };
358
+ }
359
+ async continueTurn(options = {}) {
360
+ return await this.executeTurn({
361
+ kind: "continue",
362
+ options,
363
+ appendPromptUserMessage: false,
364
+ });
365
+ }
366
+ async appendUserMessage(text) {
367
+ this.assertOpen();
368
+ const timestamp = new Date().toISOString();
369
+ const userEntryId = `user-${++this.state.turnSeq}`;
370
+ this.addEntry(this.createMessageEntry(userEntryId, this.state.currentLeafId, "user", text, timestamp));
371
+ await this.persistState?.();
372
+ return userEntryId;
373
+ }
374
+ async appendCustomMessage(input) {
375
+ this.assertOpen();
376
+ const timestamp = new Date().toISOString();
377
+ const entryId = `custom-${++this.state.turnSeq}`;
378
+ this.addEntry({
379
+ id: entryId,
380
+ parentId: this.state.currentLeafId,
381
+ type: "custom_message",
382
+ timestamp,
383
+ customType: "leitwerk",
384
+ content: input.content,
385
+ details: input.details,
386
+ });
387
+ await this.persistState?.();
388
+ return entryId;
389
+ }
390
+ async steer(text) {
391
+ this.assertOpen();
392
+ this.steers.push(text);
393
+ }
394
+ async abortTurn() {
395
+ this.assertOpen();
396
+ }
397
+ subscribe(handler) {
398
+ this.handlers.add(handler);
399
+ return () => {
400
+ this.handlers.delete(handler);
401
+ };
402
+ }
403
+ subscribeDiagnostics(handler) {
404
+ this.diagnosticHandlers.add(handler);
405
+ return () => {
406
+ this.diagnosticHandlers.delete(handler);
407
+ };
408
+ }
409
+ emitDiagnostic(diagnostic) {
410
+ for (const handler of this.diagnosticHandlers)
411
+ handler(diagnostic);
412
+ }
413
+ async close() {
414
+ await this.persistState?.();
415
+ this._closed = true;
416
+ this.handlers.clear();
417
+ this.diagnosticHandlers.clear();
418
+ }
419
+ }
420
+ export class StubPiTreeHandleFactory {
421
+ sessions = [];
422
+ toolCallScriptResolver;
423
+ seq = 0;
424
+ treeStateByFile = new Map();
425
+ constructor(options = {}) {
426
+ this.toolCallScriptResolver = options.toolCallScriptResolver;
427
+ }
428
+ async prepareManagedBootstrap(opts) {
429
+ return {
430
+ loadedResourceIds: opts.manifest.provenance.map((resource) => resource.snapshotPath),
431
+ loadedAgentsFiles: [],
432
+ loadedSkillFiles: [],
433
+ resolvedModel: { ...opts.expectedModel },
434
+ diagnostics: [],
435
+ };
436
+ }
437
+ async inspectPrimaryTree(opts) {
438
+ let treeState = this.treeStateByFile.get(opts.treeFile);
439
+ if (!treeState) {
440
+ try {
441
+ treeState = deserializeStubPiTreeState(readFileSync(opts.treeFile, "utf8"));
442
+ }
443
+ catch (error) {
444
+ if (typeof error === "object" &&
445
+ error !== null &&
446
+ "code" in error &&
447
+ error.code === "ENOENT") {
448
+ return { currentLeafId: null, entries: [] };
449
+ }
450
+ throw error;
451
+ }
452
+ }
453
+ return {
454
+ currentLeafId: treeState.currentLeafId ?? deriveStubLeafIdFromEntries(treeState),
455
+ entries: [...treeState.entries.values()].map((entry) => ({
456
+ id: entry.id,
457
+ parentId: entry.parentId,
458
+ })),
459
+ };
460
+ }
461
+ async createPrimaryTreeHandle(opts) {
462
+ const persistState = async (state) => {
463
+ this.treeStateByFile.set(opts.treeFile, state);
464
+ try {
465
+ mkdirSync(path.dirname(opts.treeFile), { recursive: true });
466
+ writeFileSync(opts.treeFile, serializeStubPiTreeState(state), "utf8");
467
+ }
468
+ catch (error) {
469
+ if (typeof error !== "object" ||
470
+ error === null ||
471
+ !("code" in error) ||
472
+ !["ENOENT", "EACCES", "EROFS", "EPERM"].includes(String(error.code))) {
473
+ throw error;
474
+ }
475
+ }
476
+ };
477
+ let treeState = this.treeStateByFile.get(opts.treeFile);
478
+ if (!treeState && opts.resume) {
479
+ try {
480
+ const persisted = readFileSync(opts.treeFile, "utf8");
481
+ treeState = deserializeStubPiTreeState(persisted);
482
+ }
483
+ catch (error) {
484
+ if (typeof error === "object" &&
485
+ error !== null &&
486
+ "code" in error &&
487
+ error.code !== "ENOENT") {
488
+ throw error;
489
+ }
490
+ }
491
+ }
492
+ treeState ??= createEmptyStubPiTreeState();
493
+ if (opts.resume) {
494
+ treeState.currentLeafId = deriveStubLeafIdFromEntries(treeState);
495
+ }
496
+ this.treeStateByFile.set(opts.treeFile, treeState);
497
+ const piHandle = new StubPiTreeHandle({
498
+ sessionId: `stub-${++this.seq}`,
499
+ treeFile: opts.treeFile,
500
+ isResumed: opts.resume,
501
+ toolCallScriptResolver: this.toolCallScriptResolver,
502
+ state: treeState,
503
+ persistState: () => persistState(treeState),
504
+ runDetails: {
505
+ availableToolNames: opts.piConfig?.availableToolNames ?? [],
506
+ },
507
+ });
508
+ this.sessions.push(piHandle);
509
+ if (!opts.resume) {
510
+ await persistState(treeState);
511
+ }
512
+ return piHandle;
513
+ }
514
+ }
515
+ //# sourceMappingURL=stub-pi-tree-handle.js.map