@godspeedai/cognate-profile-harness 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +21 -2
  3. package/package.json +34 -4
  4. package/src/index.ts +360 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,22 @@
1
- # Temporary Holding Version
1
+ # @godspeedai/cognate-profile-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
+ Reference Harness profile (spec §29.2, §35, §40.K): a pure composition of existing kernel/runtime
4
+ primitives. No kernel additions — every behaviour below is a `Component`, an `AgentDefinition`, or
5
+ plain durable-store/service calls.
6
+
7
+ | Profile component | Primitive it composes |
8
+ | --- | --- |
9
+ | `model-providers` | `providerComponent(provider)` → `fiber.provide(modelContract(provider), ...)`, capability `model.generate` |
10
+ | `tool-registry` | `toolComponent`/`skillComponent` → `fiber.provide({id:"tool.<name>", ...})`; a harness-local `Map` kept live via `fiber.effects.register` disposers, filtered through `runtime.kernel.resolve` |
11
+ | `agent-loop` | `AgentDefinition` `LOOP_AGENT` using only `ctx.invoke("model.generate", ...)` / `ctx.invoke("tool.<name>", ...)` |
12
+ | `sessions` | `runtime.service.startRun`/`.events`/`.getRun` filtered by `correlationId = "session:<id>"` |
13
+ | `storage` | `storageComponent(store)` → capability `storage.kv`, backed by CAS `DurableStore` records (collection `kv`) |
14
+ | `skills` | `skillComponent` → same `fiber.provide` mechanism as tools, several at once |
15
+ | `scheduler` | durable records (collection `schedules`) + a `setInterval` loop calling `runtime.service.startRun` |
16
+ | `sandbox` | `Bun.spawn(["bun","-e",code])` with a scrubbed `env` and a timeout `proc.kill()` |
17
+ | `subagents` | `spawnSubagent` → `ctx.invoke("subagent.start", ...)` (a component calling `runtime.service.startRun` as `system`) + `ctx.waitFor` resolved from `runtime.store.onCommitted` |
18
+
19
+ `createHarness` mounts `storage`, `sandbox`, and `subagent.start` as ordinary components on the
20
+ existing `@godspeedai/cognate-runtime-bun` kernel; providers/tools/skills are mounted the same way by callers.
21
+ Policy (`Policy`) and action authorization (`ActionPolicy`) are both allow-all by default — this is a
22
+ reference/demo harness, not a multi-tenant deployment; see `createHarness` for the exact rules.
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "@godspeedai/cognate-profile-harness",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Harness reference profile: model providers, tool registry, agent loop, sessions, storage, skills, scheduler, sandbox, replaceable services, subagents (spec §29.2). No kernel additions.",
5
+ "type": "module",
6
+ "license": "Apache-2.0",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/GodSpeedAI/Cognate.git",
10
+ "directory": "profiles/harness"
11
+ },
12
+ "engines": {
13
+ "bun": ">=1.4.0"
14
+ },
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "files": [
19
+ "src"
20
+ ],
21
+ "exports": {
22
+ ".": "./src/index.ts"
23
+ },
24
+ "dependencies": {
25
+ "@godspeedai/cognate-capabilities": "^0.1.0",
26
+ "@godspeedai/cognate-events": "^0.1.0",
27
+ "@godspeedai/cognate-kernel-api": "^0.1.0",
28
+ "@godspeedai/cognate-profile": "^0.1.0",
29
+ "@godspeedai/cognate-provider-openai-compatible": "^0.1.0",
30
+ "@godspeedai/cognate-runtime-api": "^0.1.0",
31
+ "@godspeedai/cognate-runtime-bun": "^0.1.0"
32
+ },
33
+ "devDependencies": {
34
+ "@godspeedai/cognate-provider-local": "workspace:*"
35
+ }
36
+ }
package/src/index.ts ADDED
@@ -0,0 +1,360 @@
1
+ import { modelContract } from "@godspeedai/cognate-capabilities";
2
+ import type { ModelMessage, ModelProvider, ModelResponse } from "@godspeedai/cognate-capabilities";
3
+ import type { DurableStore, Json } from "@godspeedai/cognate-events";
4
+ import { isUnavailable, rulePolicy } from "@godspeedai/cognate-kernel-api";
5
+ import type { Component, ComponentHandle, Policy } from "@godspeedai/cognate-kernel-api";
6
+ import { defineProfile } from "@godspeedai/cognate-profile";
7
+ import type { ComponentEntry, ProfileDefinition } from "@godspeedai/cognate-profile";
8
+ import type { AgentDefinition, Caller, RunContext } from "@godspeedai/cognate-runtime-api";
9
+ import { createRuntime, type GovernanceOptions, governanceFromEnv } from "@godspeedai/cognate-runtime-bun";
10
+ import type { ActionPolicy, Runtime } from "@godspeedai/cognate-runtime-bun";
11
+
12
+ export const LOOP_AGENT = "agent.loop";
13
+
14
+ // The harness composes registered components only; no kernel primitives are added (spec §29.2, §40.K).
15
+ const HARNESS_COMPONENTS = ["model-providers", "tool-registry", "agent-loop", "sessions", "storage", "skills", "scheduler", "sandbox", "subagents"] as const;
16
+
17
+ export const harnessProfile: ProfileDefinition = defineProfile({
18
+ name: "harness",
19
+ description: "Reference harness: model providers, tool registry, agent loop, sessions, storage, skills, scheduler, sandbox, and subagents (spec §29.2).",
20
+ components: HARNESS_COMPONENTS,
21
+ });
22
+
23
+ export const harnessRegistry: readonly ComponentEntry<unknown>[] = HARNESS_COMPONENTS.map((name) => ({
24
+ name,
25
+ package: "@godspeedai/cognate-profile-harness",
26
+ supported: true,
27
+ contribute: () => undefined,
28
+ }));
29
+
30
+ /** A tool is a capability `tool.<name>` plus a description and JSON Schema the loop offers to the model. */
31
+ export interface ToolSpec {
32
+ readonly name: string;
33
+ readonly description: string;
34
+ readonly inputSchema: { readonly [key: string]: Json };
35
+ readonly handler: (input: Json) => Json | Promise<Json>;
36
+ /** Other capabilities this tool requires (dependency-driven activation, spec §35). */
37
+ readonly requires?: Readonly<Record<string, { readonly capability: string }>>;
38
+ }
39
+
40
+ /** Full tool metadata behind a mounted `tool.<name>` / `skill:<name>` component, keyed by component identity. */
41
+ const toolSpecOf = new WeakMap<Component, ToolSpec>();
42
+ const skillSpecOf = new WeakMap<Component, readonly ToolSpec[]>();
43
+
44
+ /** Kernel component publishing one tool; mount/dispose it to add/remove the tool live. */
45
+ export function toolComponent(tool: ToolSpec): Component {
46
+ const component: Component = {
47
+ id: `tool:${tool.name}`,
48
+ requires: tool.requires,
49
+ provides: [{ id: `tool.${tool.name}`, version: "1.0.0", attributes: { description: tool.description } }],
50
+ activate(fiber) {
51
+ fiber.provide({ id: `tool.${tool.name}`, version: "1.0.0", attributes: { description: tool.description } }, (input) => tool.handler(input as Json));
52
+ },
53
+ };
54
+ toolSpecOf.set(component, tool);
55
+ return component;
56
+ }
57
+
58
+ /** A skill/extension: a named bundle of tools mounted as one component. */
59
+ export function skillComponent(skill: { readonly name: string; readonly tools: readonly ToolSpec[] }): Component {
60
+ const component: Component = {
61
+ id: `skill:${skill.name}`,
62
+ provides: skill.tools.map((tool) => ({ id: `tool.${tool.name}`, version: "1.0.0", attributes: { description: tool.description } })),
63
+ activate(fiber) {
64
+ for (const tool of skill.tools) fiber.provide({ id: `tool.${tool.name}`, version: "1.0.0", attributes: { description: tool.description } }, (input) => tool.handler(input as Json));
65
+ },
66
+ };
67
+ skillSpecOf.set(component, skill.tools);
68
+ return component;
69
+ }
70
+
71
+ /** Publishes `model.generate` for a provider (replaceable: dispose one, mount another). */
72
+ export function providerComponent(provider: ModelProvider): Component {
73
+ const contract = modelContract(provider);
74
+ return {
75
+ id: `model-provider:${provider.id}`,
76
+ provides: [contract],
77
+ activate(fiber) {
78
+ fiber.provide(contract, (input, context) => provider.generate(input as Parameters<ModelProvider["generate"]>[0], context.signal));
79
+ },
80
+ };
81
+ }
82
+
83
+ /** Publishes `storage.kv` ({op:"get"|"set"|"delete", key, value?}) backed by durable records, partitioned by the caller's tenant (§32). */
84
+ export function storageComponent(store: DurableStore): Component {
85
+ return {
86
+ id: "storage:kv",
87
+ provides: [{ id: "storage.kv", version: "1.0.0" }],
88
+ activate(fiber) {
89
+ fiber.provide({ id: "storage.kv", version: "1.0.0" }, async (rawInput, ctx) => {
90
+ const input = rawInput as { readonly op: "get" | "set" | "delete"; readonly key: string; readonly value?: Json };
91
+ const id = `${ctx.tenant}/${input.key}`;
92
+ if (input.op === "get") {
93
+ const record = await store.getRecord("kv", id);
94
+ return record && (record.value as { present: boolean }).present ? (record.value as { value: Json }).value : null;
95
+ }
96
+ for (;;) {
97
+ const existing = await store.getRecord("kv", id);
98
+ const expectedVersion = existing?.version ?? 0;
99
+ const value = input.op === "set" ? (input.value ?? null) : null;
100
+ try {
101
+ await store.commit({ appends: [], records: [{ collection: "kv", id, expectedVersion, value: { present: input.op === "set", value } }] });
102
+ return value;
103
+ } catch (error) {
104
+ if ((error as Error).name === "RecordConflictError") continue;
105
+ throw error;
106
+ }
107
+ }
108
+ });
109
+ },
110
+ };
111
+ }
112
+
113
+ /** Publishes `subagent.start`: starts a run as the system caller with a durable idempotency key. */
114
+ function subagentStartComponent(runtime: Runtime): Component {
115
+ return {
116
+ id: "subagent:start",
117
+ provides: [{ id: "subagent.start", version: "1.0.0" }],
118
+ activate(fiber) {
119
+ fiber.provide({ id: "subagent.start", version: "1.0.0" }, async (rawInput, ctx) => {
120
+ // The child runs in the invoking caller's tenant (HandlerContext.tenant, spec §32).
121
+ const input = rawInput as { readonly agent: string; readonly input: Json; readonly key: string };
122
+ const view = await runtime.service.startRun({ actor: { id: "system", kind: "system" }, tenant: ctx.tenant }, { agent: input.agent, input: input.input, idempotencyKey: input.key });
123
+ return { runId: view.runId };
124
+ });
125
+ },
126
+ };
127
+ }
128
+
129
+ /** Publishes `sandbox.exec`: a scrubbed, timed-out Bun subprocess. */
130
+ function sandboxComponent(limits: { readonly timeoutMs: number; readonly maxOutputBytes: number }): Component {
131
+ return {
132
+ id: "sandbox:exec",
133
+ provides: [{ id: "sandbox.exec", version: "1.0.0" }],
134
+ activate(fiber) {
135
+ fiber.provide({ id: "sandbox.exec", version: "1.0.0" }, async (rawInput) => {
136
+ const { code } = rawInput as { readonly code: string };
137
+ const proc = Bun.spawn(["bun", "-e", code], { env: { PATH: process.env.PATH ?? "" }, stdout: "pipe", stderr: "pipe" });
138
+ let timedOut = false;
139
+ const timer = setTimeout(() => {
140
+ timedOut = true;
141
+ proc.kill();
142
+ }, limits.timeoutMs);
143
+ const [stdout, stderr, exitCode] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
144
+ clearTimeout(timer);
145
+ const truncate = (text: string): string => {
146
+ const bytes = new TextEncoder().encode(text);
147
+ return bytes.length <= limits.maxOutputBytes ? text : new TextDecoder().decode(bytes.slice(0, limits.maxOutputBytes));
148
+ };
149
+ return { exitCode, stdout: truncate(stdout), stderr: truncate(stderr), timedOut };
150
+ });
151
+ },
152
+ };
153
+ }
154
+
155
+ export interface HarnessOptions {
156
+ readonly store: string;
157
+ readonly instructions?: string;
158
+ /** Maximum model/tool iterations per loop run. */
159
+ readonly maxSteps?: number;
160
+ /** Sandbox limits for `sandbox.exec` (Bun subprocess, scrubbed environment). */
161
+ readonly sandbox?: { readonly timeoutMs: number; readonly maxOutputBytes: number };
162
+ /** Identity the harness acts as for send/session/schedule (default LOCAL_OPERATOR). */
163
+ readonly caller?: Caller;
164
+ /** Additional agents (e.g. subagents) served by the runtime alongside the loop agent. */
165
+ readonly agents?: readonly AgentDefinition[];
166
+ /**
167
+ * Governance of consequential operations. Default: taken from the environment (`COGNATE_GOVERNANCE`,
168
+ * `COGNATE_SEA_FORGE_SOCKET`, `COGNATE_WORLD_REF`); with nothing set it is `off` (local policy only).
169
+ */
170
+ readonly governance?: GovernanceOptions;
171
+ }
172
+
173
+ export interface Harness {
174
+ readonly runtime: Runtime;
175
+ /** Handle of the built-in `storage.kv` component (dispose/remount it to exercise §35). */
176
+ readonly storage: ComponentHandle;
177
+ /** Mount a component in the harness root scope (providers, tools, skills). */
178
+ mount(component: Component): Promise<ComponentHandle>;
179
+ /** Start the loop agent in a session (sessions group runs by `session:<id>` correlation). */
180
+ send(sessionId: string, message: string): Promise<string>;
181
+ /** Runs of a session, oldest first, with their status and output (a projection over run events). */
182
+ session(sessionId: string): Promise<readonly { readonly runId: string; readonly status: string; readonly output: Json }[]>;
183
+ /** Start `agent` with `input` at or after `at` (epoch ms), durably. Returns a schedule id. */
184
+ schedule(agent: string, input: Json, at: number): Promise<string>;
185
+ close(): Promise<void>;
186
+ }
187
+
188
+ const DEFAULT_SANDBOX = { timeoutMs: 30_000, maxOutputBytes: 200_000 };
189
+ const DEFAULT_MAX_STEPS = 8;
190
+ /** Default operator identity for a local, single-user harness; pass `caller` to run as someone else. */
191
+ export const LOCAL_OPERATOR: Caller = { actor: { id: "operator", kind: "user" }, tenant: "local" };
192
+
193
+ function sessionInputOf(input: Json): string | undefined {
194
+ if (typeof input !== "object" || input === null || Array.isArray(input)) return undefined;
195
+ const sessionId = (input as { readonly sessionId?: Json }).sessionId;
196
+ return typeof sessionId === "string" ? sessionId : undefined;
197
+ }
198
+
199
+ /**
200
+ * Build a harness. Built-in components: the loop agent (model → tool calls → tools → model, tools discovered from the
201
+ * kernel each step), `storage.kv` backed by durable records, `sandbox.exec`, the scheduler, and sessions.
202
+ */
203
+ export async function createHarness(options: HarnessOptions): Promise<Harness> {
204
+ const maxSteps = options.maxSteps ?? DEFAULT_MAX_STEPS;
205
+ const HARNESS_USER: Caller = options.caller ?? LOCAL_OPERATOR;
206
+ const HARNESS_SYSTEM: Caller = { actor: { id: "system", kind: "system" }, tenant: HARNESS_USER.tenant };
207
+ const sandboxLimits = options.sandbox ?? DEFAULT_SANDBOX;
208
+
209
+ // This harness's own tool registry: name -> spec, kept live by effects registered on tool/skill activation.
210
+ const tools = new Map<string, ToolSpec>();
211
+
212
+ function withToolRegistry(component: Component): Component {
213
+ const specs = toolSpecOf.has(component) ? [toolSpecOf.get(component)!] : skillSpecOf.get(component);
214
+ if (!specs) return component;
215
+ return {
216
+ ...component,
217
+ async activate(fiber) {
218
+ await component.activate(fiber);
219
+ for (const spec of specs) tools.set(spec.name, spec);
220
+ fiber.effects.register(() => {
221
+ for (const spec of specs) tools.delete(spec.name);
222
+ });
223
+ },
224
+ };
225
+ }
226
+
227
+ function offeredTools(): ToolSpec[] {
228
+ const offered: ToolSpec[] = [];
229
+ for (const [name, spec] of tools) {
230
+ const lease = runtime.kernel.resolve({ capability: `tool.${name}` });
231
+ if (!isUnavailable(lease) && lease.valid) offered.push(spec);
232
+ }
233
+ return offered;
234
+ }
235
+
236
+ const loopAgent: AgentDefinition = {
237
+ id: LOOP_AGENT,
238
+ version: "1.0.0",
239
+ async run(input, ctx) {
240
+ const { message } = input as { readonly message: string; readonly sessionId?: string };
241
+ const messages: ModelMessage[] = [];
242
+ if (options.instructions) messages.push({ role: "system", content: options.instructions });
243
+ messages.push({ role: "user", content: message });
244
+ const steps: Json[] = [];
245
+ for (let step = 0; step < maxSteps; step++) {
246
+ const toolDefs = offeredTools().map((tool) => ({ name: tool.name, description: tool.description, inputSchema: tool.inputSchema }));
247
+ const response = (await ctx.invoke("model.generate", { messages, tools: toolDefs } as unknown as Json)) as unknown as ModelResponse;
248
+ if (response.finishReason !== "tool_calls" || response.toolCalls.length === 0) return { answer: response.message.content, steps };
249
+ messages.push({ role: "assistant", content: response.message.content, toolCalls: response.toolCalls });
250
+ for (const call of response.toolCalls) {
251
+ const result = await ctx.invoke(`tool.${call.name}`, call.arguments);
252
+ steps.push({ tool: call.name, arguments: call.arguments, result });
253
+ messages.push({ role: "tool", content: JSON.stringify(result), toolCallId: call.id });
254
+ }
255
+ }
256
+ return { answer: "max steps reached", steps };
257
+ },
258
+ };
259
+
260
+ const policy: Policy = rulePolicy("harness-allow-all", [() => ({ allow: true, policyId: "harness-allow-all", reason: "harness policy allows all invocations by default (spec §29.2)" })]);
261
+ const actions: ActionPolicy = { authorize: () => ({ allow: true, reason: "harness actions policy allows system and default users (spec §29.2)" }) };
262
+
263
+ const runtime = await createRuntime({ store: options.store, policy, actions, governance: options.governance ?? governanceFromEnv(process.env), agents: [loopAgent, ...(options.agents ?? [])] });
264
+
265
+ async function mount(component: Component): Promise<ComponentHandle> {
266
+ const handle = await runtime.kernel.mount(withToolRegistry(component));
267
+ await handle.waitFor("ACTIVE", 10_000).catch(() => {});
268
+ return handle;
269
+ }
270
+
271
+ const storageHandle = await mount(storageComponent(runtime.store));
272
+ await mount(sandboxComponent(sandboxLimits));
273
+ await mount(subagentStartComponent(runtime));
274
+
275
+ // Resolve any subagent `run_completion` continuation whose child run `runId` is already terminal.
276
+ async function resolveSubagentCompletion(runId: string): Promise<void> {
277
+ const view = await runtime.service.getRun(HARNESS_SYSTEM, { runId }).catch(() => undefined);
278
+ if (!view || view.status === "running" || view.status === "waiting") return;
279
+ for (const continuation of await runtime.service.listContinuations(HARNESS_SYSTEM, { status: "OPEN" })) {
280
+ if (continuation.type !== "subagent") continue;
281
+ const condition = continuation.condition as { readonly kind?: string; readonly runId?: string };
282
+ if (condition.kind !== "run_completion" || condition.runId !== runId) continue;
283
+ await runtime.service
284
+ .resolveContinuation(HARNESS_SYSTEM, { continuationId: continuation.id, action: "resume", input: view.output, idempotencyKey: `subagent-complete:${continuation.id}` })
285
+ .catch(() => {});
286
+ }
287
+ }
288
+
289
+ // A child may finish before its parent's `run_completion` continuation is even durably opened (ordinary
290
+ // race) or before the harness restarts and resubscribes (crash/restart window); check both directions.
291
+ async function checkAlreadyResolved(parentRunId: string): Promise<void> {
292
+ for (const continuation of await runtime.service.listContinuations(HARNESS_SYSTEM, { runId: parentRunId, status: "OPEN" })) {
293
+ if (continuation.type !== "subagent") continue;
294
+ const condition = continuation.condition as { readonly kind?: string; readonly runId?: string };
295
+ if (condition.kind === "run_completion" && condition.runId) await resolveSubagentCompletion(condition.runId);
296
+ }
297
+ }
298
+
299
+ const unsubscribeCommits = runtime.store.onCommitted((events) => {
300
+ for (const event of events) {
301
+ if (!event.runId) continue;
302
+ if (event.eventType === "run.completed" || event.eventType === "run.failed" || event.eventType === "run.cancelled") void resolveSubagentCompletion(event.runId);
303
+ if (event.eventType === "run.waiting") void checkAlreadyResolved(event.runId);
304
+ }
305
+ });
306
+
307
+ // On start, a child may already have finished before its continuation was durably recorded (crash/restart window).
308
+ for (const continuation of await runtime.service.listContinuations(HARNESS_SYSTEM, { status: "OPEN" })) {
309
+ if (continuation.type !== "subagent") continue;
310
+ const condition = continuation.condition as { readonly kind?: string; readonly runId?: string };
311
+ if (condition.kind === "run_completion" && condition.runId) await resolveSubagentCompletion(condition.runId);
312
+ }
313
+
314
+ async function send(sessionId: string, message: string): Promise<string> {
315
+ const view = await runtime.service.startRun(HARNESS_USER, { agent: LOOP_AGENT, input: { message, sessionId }, idempotencyKey: crypto.randomUUID(), correlationId: `session:${sessionId}` });
316
+ return view.runId;
317
+ }
318
+
319
+ async function session(sessionId: string): Promise<readonly { readonly runId: string; readonly status: string; readonly output: Json }[]> {
320
+ // Served by the runtime's run index (DEBT-019), not an event-log scan.
321
+ const runs = await runtime.service.listRuns(HARNESS_USER, { correlationId: `session:${sessionId}` });
322
+ return runs.map((view) => ({ runId: view.runId, status: view.status, output: view.output }));
323
+ }
324
+
325
+ async function schedule(agent: string, input: Json, at: number): Promise<string> {
326
+ const id = crypto.randomUUID();
327
+ await runtime.store.commit({ appends: [], records: [{ collection: "schedules", id, expectedVersion: 0, value: { agent, input, at, started: false } }] });
328
+ return id;
329
+ }
330
+
331
+ async function tickScheduler(): Promise<void> {
332
+ const now = Date.now();
333
+ for (const record of await runtime.store.listRecords("schedules", { started: false })) {
334
+ const value = record.value as { readonly agent: string; readonly input: Json; readonly at: number };
335
+ if (value.at > now) continue;
336
+ try {
337
+ await runtime.store.commit({ appends: [], records: [{ collection: "schedules", id: record.id, expectedVersion: record.version, value: { ...value, started: true } }] });
338
+ } catch {
339
+ continue; // lost the race to another tick; the winner starts it.
340
+ }
341
+ const sessionId = sessionInputOf(value.input);
342
+ await runtime.service.startRun(HARNESS_SYSTEM, { agent: value.agent, input: value.input, idempotencyKey: record.id, ...(sessionId ? { correlationId: `session:${sessionId}` } : {}) }).catch(() => {});
343
+ }
344
+ }
345
+ const schedulerTimer = setInterval(() => void tickScheduler().catch(() => {}), 20);
346
+
347
+ async function close(): Promise<void> {
348
+ clearInterval(schedulerTimer);
349
+ unsubscribeCommits();
350
+ await runtime.close();
351
+ }
352
+
353
+ return { runtime, storage: storageHandle, mount, send, session, schedule, close };
354
+ }
355
+
356
+ /** Durably start a subagent run from inside a run and wait for its output (resumes across restarts). */
357
+ export async function spawnSubagent(ctx: RunContext, id: string, agent: string, input: Json): Promise<Json> {
358
+ const { runId } = (await ctx.invoke("subagent.start", { agent, input, key: `${ctx.runId}:${id}` })) as { readonly runId: string };
359
+ return ctx.waitFor(id, { type: "subagent", condition: { kind: "run_completion", runId }, payload: { agent } });
360
+ }