@hydraharness/harness-subagent 0.1.1-rc.5
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 +155 -0
- package/lib/index.js +2743 -0
- package/lib/invariant.js +76 -0
- package/lib/types/activation-setup-registry.d.ts +57 -0
- package/lib/types/activation-setup-registry.js +148 -0
- package/lib/types/assistant-output.d.ts +48 -0
- package/lib/types/assistant-output.js +72 -0
- package/lib/types/budget.d.ts +34 -0
- package/lib/types/budget.js +54 -0
- package/lib/types/child-agent.d.ts +139 -0
- package/lib/types/child-agent.js +169 -0
- package/lib/types/client.d.ts +7 -0
- package/lib/types/client.js +7 -0
- package/lib/types/continuation.d.ts +457 -0
- package/lib/types/continuation.js +1157 -0
- package/lib/types/depth.d.ts +31 -0
- package/lib/types/depth.js +39 -0
- package/lib/types/descriptor-seed.d.ts +21 -0
- package/lib/types/descriptor-seed.js +24 -0
- package/lib/types/descriptor.d.ts +139 -0
- package/lib/types/descriptor.js +189 -0
- package/lib/types/error.d.ts +11 -0
- package/lib/types/error.js +14 -0
- package/lib/types/index.d.ts +296 -0
- package/lib/types/index.js +374 -0
- package/lib/types/invariant.d.ts +13 -0
- package/lib/types/invariant.js +91 -0
- package/lib/types/lifecycle.d.ts +113 -0
- package/lib/types/lifecycle.js +177 -0
- package/lib/types/list-children.d.ts +112 -0
- package/lib/types/list-children.js +316 -0
- package/lib/types/out-of-process.d.ts +117 -0
- package/lib/types/out-of-process.js +211 -0
- package/lib/types/projection-types.d.ts +60 -0
- package/lib/types/projection-types.js +7 -0
- package/lib/types/projection.d.ts +95 -0
- package/lib/types/projection.js +150 -0
- package/lib/types/run-settlement.d.ts +17 -0
- package/lib/types/run-settlement.js +66 -0
- package/lib/types/types.d.ts +315 -0
- package/lib/types/types.js +19 -0
- package/package.json +112 -0
package/lib/invariant.js
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
//#region lib/types/invariant.js
|
|
2
|
+
/** Package-owned subagent registry and lifecycle invariants. @module @hydraharness/harness-subagent/invariant */
|
|
3
|
+
const PACKAGE_NAME = "@hydraharness/harness-subagent";
|
|
4
|
+
/** Cordis companion plugin name. */
|
|
5
|
+
const name = "subagent-invariant";
|
|
6
|
+
/** Service required before the companion can reserve package ownership. */
|
|
7
|
+
const inject = ["invariants"];
|
|
8
|
+
/** Assert that a terminal lifecycle payload matches its start identity. */
|
|
9
|
+
function validateRunEnd(start, end, fail) {
|
|
10
|
+
if (start.provider !== end.provider || start.id !== end.id || start.local !== end.local) fail(`subagent/end identity diverges from subagent/start for run ${JSON.stringify(end.runId)}`);
|
|
11
|
+
}
|
|
12
|
+
/** Install provider-registry and start/end pairing checks. */
|
|
13
|
+
const install = Object.assign((ctx, fail) => {
|
|
14
|
+
const providers = new Set(ctx.subagents.list());
|
|
15
|
+
const runs = /* @__PURE__ */ new Map();
|
|
16
|
+
const stagedProviders = /* @__PURE__ */ new WeakSet();
|
|
17
|
+
const stagedRemovals = /* @__PURE__ */ new Set();
|
|
18
|
+
const stagedStarts = /* @__PURE__ */ new WeakSet();
|
|
19
|
+
const stagedEnds = /* @__PURE__ */ new WeakSet();
|
|
20
|
+
ctx.on("internal/dispatch", (_mode, eventName, args) => {
|
|
21
|
+
if (eventName === "subagent/provider-added") {
|
|
22
|
+
const provider = args[0];
|
|
23
|
+
if (provider.name.length === 0) fail("subagent provider names must be non-empty");
|
|
24
|
+
if (providers.has(provider.name)) fail(`subagent/provider-added repeated ${JSON.stringify(provider.name)}`);
|
|
25
|
+
stagedProviders.add(provider);
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
if (eventName === "subagent/provider-removed") {
|
|
29
|
+
const providerName = args[0];
|
|
30
|
+
if (!providers.has(providerName)) fail(`subagent/provider-removed names unknown provider ${JSON.stringify(providerName)}`);
|
|
31
|
+
stagedRemovals.add(providerName);
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
if (eventName === "subagent/start") {
|
|
35
|
+
const info = args[0];
|
|
36
|
+
if (info.provider.length === 0 || String(info.runId).length === 0 || String(info.id).length === 0) fail("subagent/start provider, runId, and child id must be non-empty");
|
|
37
|
+
if (runs.has(info.runId)) fail(`subagent/start repeated run id ${JSON.stringify(info.runId)}`);
|
|
38
|
+
stagedStarts.add(info);
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
if (eventName !== "subagent/end") return;
|
|
42
|
+
const info = args[0];
|
|
43
|
+
const start = runs.get(info.runId);
|
|
44
|
+
if (start === void 0) fail(`subagent/end has no matching subagent/start for run ${JSON.stringify(info.runId)}`);
|
|
45
|
+
validateRunEnd(start, info, fail);
|
|
46
|
+
stagedEnds.add(info);
|
|
47
|
+
}, { global: true });
|
|
48
|
+
ctx.on("subagent/provider-added", (provider) => {
|
|
49
|
+
/* v8 ignore next -- internal/dispatch stages the same provider object */
|
|
50
|
+
if (!stagedProviders.delete(provider)) return;
|
|
51
|
+
providers.add(provider.name);
|
|
52
|
+
}, { global: true });
|
|
53
|
+
ctx.on("subagent/provider-removed", (providerName) => {
|
|
54
|
+
/* v8 ignore next -- internal/dispatch stages the same provider name */
|
|
55
|
+
if (!stagedRemovals.delete(providerName)) return;
|
|
56
|
+
providers.delete(providerName);
|
|
57
|
+
}, { global: true });
|
|
58
|
+
ctx.on("subagent/start", (info) => {
|
|
59
|
+
/* v8 ignore next -- internal/dispatch stages the same lifecycle object */
|
|
60
|
+
if (!stagedStarts.delete(info)) return;
|
|
61
|
+
runs.set(info.runId, info);
|
|
62
|
+
}, { global: true });
|
|
63
|
+
ctx.on("subagent/end", (info) => {
|
|
64
|
+
/* v8 ignore next -- internal/dispatch stages the same lifecycle object */
|
|
65
|
+
if (!stagedEnds.delete(info)) return;
|
|
66
|
+
runs.delete(info.runId);
|
|
67
|
+
}, { global: true });
|
|
68
|
+
}, { inject: ["subagents"] });
|
|
69
|
+
/**
|
|
70
|
+
* Register the subagent invariant companion.
|
|
71
|
+
* @param ctx - Cordis context carrying the invariant service.
|
|
72
|
+
* @returns the installed registration's disposer after setup succeeds.
|
|
73
|
+
*/
|
|
74
|
+
const apply = (ctx) => Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install));
|
|
75
|
+
//#endregion
|
|
76
|
+
export { apply, inject, name };
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Internal registry of deployment capabilities composed into every continuable
|
|
3
|
+
* child's unpublished creation context.
|
|
4
|
+
*
|
|
5
|
+
* A contribution grants a child-scoped capability without teaching the
|
|
6
|
+
* continuation manager which capabilities exist. The manager owns residency;
|
|
7
|
+
* this registry owns the join between plugin lifetime, unpublished setup, and
|
|
8
|
+
* Activation disposal, so no installation outlives either owner and no removed
|
|
9
|
+
* contribution can be installed after revocation reports completion.
|
|
10
|
+
*
|
|
11
|
+
* @module @hydraharness/harness-subagent/activation-setup-registry
|
|
12
|
+
*/
|
|
13
|
+
import type { Context } from '@hydraharness/cordis';
|
|
14
|
+
import type { AgentSetupCommit } from '@hydraharness/harness-agent';
|
|
15
|
+
/**
|
|
16
|
+
* One deployment capability installed into a continuable child's unpublished
|
|
17
|
+
* creation context. It composes synchronously before publication and returns
|
|
18
|
+
* the disposer for exactly that installation.
|
|
19
|
+
* @param childCtx - the child's unpublished scoped context.
|
|
20
|
+
* @returns the disposer revoking this installation.
|
|
21
|
+
*/
|
|
22
|
+
export type ContinuableSetupContribution = (childCtx: Context) => () => void;
|
|
23
|
+
/**
|
|
24
|
+
* Owns continuable-child setup registrations, installations, rollback, child
|
|
25
|
+
* cleanup, and immediate live revocation.
|
|
26
|
+
*/
|
|
27
|
+
export declare class SubagentActivationSetupRegistry {
|
|
28
|
+
/** Live contributions in installation order. */
|
|
29
|
+
private readonly registrations;
|
|
30
|
+
/** Child context to its live installations. */
|
|
31
|
+
private readonly byChild;
|
|
32
|
+
/**
|
|
33
|
+
* Register one contribution.
|
|
34
|
+
* @param contribution - synchronous child-scope installer.
|
|
35
|
+
* @returns an idempotent registration undo.
|
|
36
|
+
* @throws after attempting every installation when any disposer fails.
|
|
37
|
+
*/
|
|
38
|
+
register(contribution: ContinuableSetupContribution): () => void;
|
|
39
|
+
/**
|
|
40
|
+
* Install every live contribution into one unpublished child context.
|
|
41
|
+
* @param childCtx - the child's unpublished scoped context.
|
|
42
|
+
* @returns the provisioning commit consumed at Agent publication.
|
|
43
|
+
*/
|
|
44
|
+
apply(childCtx: Context): AgentSetupCommit;
|
|
45
|
+
/** Release every remaining installation owned by one disposed child scope. */
|
|
46
|
+
private releaseChild;
|
|
47
|
+
/**
|
|
48
|
+
* Release a batch completely before reporting disposer failures.
|
|
49
|
+
* @param installations - records to release.
|
|
50
|
+
* @param during - operation name for diagnostics.
|
|
51
|
+
*/
|
|
52
|
+
private releaseAll;
|
|
53
|
+
/** Drop one installation from both indices and dispose it exactly once. */
|
|
54
|
+
private release;
|
|
55
|
+
}
|
|
56
|
+
export default SubagentActivationSetupRegistry;
|
|
57
|
+
//# sourceMappingURL=activation-setup-registry.d.ts.map
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Internal registry of deployment capabilities composed into every continuable
|
|
3
|
+
* child's unpublished creation context.
|
|
4
|
+
*
|
|
5
|
+
* A contribution grants a child-scoped capability without teaching the
|
|
6
|
+
* continuation manager which capabilities exist. The manager owns residency;
|
|
7
|
+
* this registry owns the join between plugin lifetime, unpublished setup, and
|
|
8
|
+
* Activation disposal, so no installation outlives either owner and no removed
|
|
9
|
+
* contribution can be installed after revocation reports completion.
|
|
10
|
+
*
|
|
11
|
+
* @module @hydraharness/harness-subagent/activation-setup-registry
|
|
12
|
+
*/
|
|
13
|
+
import { errorChain } from '@hydraharness/harness-llm';
|
|
14
|
+
import { SubagentError } from "./error.js";
|
|
15
|
+
/** Re-read mutable removal state after a contribution may have revoked itself. */
|
|
16
|
+
function isRemoved(registration) {
|
|
17
|
+
return registration.removed;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Owns continuable-child setup registrations, installations, rollback, child
|
|
21
|
+
* cleanup, and immediate live revocation.
|
|
22
|
+
*/
|
|
23
|
+
export class SubagentActivationSetupRegistry {
|
|
24
|
+
/** Live contributions in installation order. */
|
|
25
|
+
registrations = new Set();
|
|
26
|
+
/** Child context to its live installations. */
|
|
27
|
+
byChild = new Map();
|
|
28
|
+
/**
|
|
29
|
+
* Register one contribution.
|
|
30
|
+
* @param contribution - synchronous child-scope installer.
|
|
31
|
+
* @returns an idempotent registration undo.
|
|
32
|
+
* @throws after attempting every installation when any disposer fails.
|
|
33
|
+
*/
|
|
34
|
+
register(contribution) {
|
|
35
|
+
const registration = { contribution, removed: false, installations: new Set() };
|
|
36
|
+
this.registrations.add(registration);
|
|
37
|
+
return () => {
|
|
38
|
+
if (registration.removed)
|
|
39
|
+
return;
|
|
40
|
+
// Close before disposal so a snapshotted apply() cannot install after
|
|
41
|
+
// revocation reports completion.
|
|
42
|
+
registration.removed = true;
|
|
43
|
+
this.registrations.delete(registration);
|
|
44
|
+
this.releaseAll([...registration.installations], 'contribution removal');
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Install every live contribution into one unpublished child context.
|
|
49
|
+
* @param childCtx - the child's unpublished scoped context.
|
|
50
|
+
* @returns the provisioning commit consumed at Agent publication.
|
|
51
|
+
*/
|
|
52
|
+
apply(childCtx) {
|
|
53
|
+
const state = { installations: [], invalidated: false };
|
|
54
|
+
try {
|
|
55
|
+
for (const registration of [...this.registrations]) {
|
|
56
|
+
/* v8 ignore next -- only a synchronous re-entrant revocation of an
|
|
57
|
+
* already-snapshotted registration reaches this guard. */
|
|
58
|
+
if (registration.removed)
|
|
59
|
+
continue;
|
|
60
|
+
const installation = {
|
|
61
|
+
registration,
|
|
62
|
+
childCtx,
|
|
63
|
+
dispose: registration.contribution(childCtx),
|
|
64
|
+
released: false,
|
|
65
|
+
transaction: state,
|
|
66
|
+
};
|
|
67
|
+
registration.installations.add(installation);
|
|
68
|
+
state.installations.push(installation);
|
|
69
|
+
let indexed = this.byChild.get(childCtx);
|
|
70
|
+
if (indexed === undefined) {
|
|
71
|
+
indexed = new Set();
|
|
72
|
+
this.byChild.set(childCtx, indexed);
|
|
73
|
+
}
|
|
74
|
+
indexed.add(installation);
|
|
75
|
+
// An installer may revoke itself before its installation record exists.
|
|
76
|
+
// Dispose that escaped record and invalidate the provisioning batch.
|
|
77
|
+
if (isRemoved(registration))
|
|
78
|
+
this.release(installation);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
catch (error) {
|
|
82
|
+
// Keep the installer failure authoritative, but attempt every rollback.
|
|
83
|
+
try {
|
|
84
|
+
this.releaseAll([...state.installations], 'setup rollback');
|
|
85
|
+
}
|
|
86
|
+
catch (releaseFailure) {
|
|
87
|
+
/* v8 ignore next -- requires independent installer and rollback faults. */
|
|
88
|
+
void releaseFailure;
|
|
89
|
+
}
|
|
90
|
+
throw error;
|
|
91
|
+
}
|
|
92
|
+
childCtx.effect(() => () => { this.releaseChild(childCtx); }, 'subagents.activationSetup()');
|
|
93
|
+
return {
|
|
94
|
+
commit: () => {
|
|
95
|
+
if (state.invalidated) {
|
|
96
|
+
throw new SubagentError('a continuable-subagent setup contribution was revoked while this child was being built; '
|
|
97
|
+
+ 'the child was not established', 'ACTIVATION_SETUP_REVOKED');
|
|
98
|
+
}
|
|
99
|
+
for (const installation of state.installations)
|
|
100
|
+
installation.transaction = undefined;
|
|
101
|
+
},
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
/** Release every remaining installation owned by one disposed child scope. */
|
|
105
|
+
releaseChild(childCtx) {
|
|
106
|
+
const indexed = this.byChild.get(childCtx) ?? [];
|
|
107
|
+
this.releaseAll([...indexed], 'child scope disposal');
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Release a batch completely before reporting disposer failures.
|
|
111
|
+
* @param installations - records to release.
|
|
112
|
+
* @param during - operation name for diagnostics.
|
|
113
|
+
*/
|
|
114
|
+
releaseAll(installations, during) {
|
|
115
|
+
const failures = [];
|
|
116
|
+
for (const installation of installations) {
|
|
117
|
+
try {
|
|
118
|
+
this.release(installation);
|
|
119
|
+
}
|
|
120
|
+
catch (error) {
|
|
121
|
+
failures.push(error);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
if (failures.length === 0)
|
|
125
|
+
return;
|
|
126
|
+
throw new SubagentError(`continuable-subagent setup ${during} failed to release ${failures.length} installation(s): `
|
|
127
|
+
+ failures.map(failure => errorChain(failure)).join('; '), 'ACTIVATION_SETUP_RELEASE_FAILED');
|
|
128
|
+
}
|
|
129
|
+
/** Drop one installation from both indices and dispose it exactly once. */
|
|
130
|
+
release(installation) {
|
|
131
|
+
if (installation.released)
|
|
132
|
+
return;
|
|
133
|
+
installation.released = true;
|
|
134
|
+
installation.registration.installations.delete(installation);
|
|
135
|
+
const indexed = this.byChild.get(installation.childCtx);
|
|
136
|
+
/* v8 ignore next 4 -- every live installation is indexed until this method removes it. */
|
|
137
|
+
if (indexed !== undefined) {
|
|
138
|
+
indexed.delete(installation);
|
|
139
|
+
if (indexed.size === 0)
|
|
140
|
+
this.byChild.delete(installation.childCtx);
|
|
141
|
+
}
|
|
142
|
+
if (installation.transaction !== undefined)
|
|
143
|
+
installation.transaction.invalidated = true;
|
|
144
|
+
installation.dispose();
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
export default SubagentActivationSetupRegistry;
|
|
148
|
+
//# sourceMappingURL=activation-setup-registry.js.map
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Canonical selection of a child's final assistant output. Backend run results
|
|
3
|
+
* and `subagent/end.lastAssistantMessage` apply the same rule: select the last
|
|
4
|
+
* non-empty assistant message. An empty-content message records usage only
|
|
5
|
+
* when the loop appends it after a max-tokens step with no executable blocks,
|
|
6
|
+
* so it does not replace earlier output. If no non-empty message exists,
|
|
7
|
+
* select the accumulated assistant text. Selection is independent of the
|
|
8
|
+
* run's stop reason.
|
|
9
|
+
*
|
|
10
|
+
* @module @hydraharness/harness-subagent/assistant-output
|
|
11
|
+
*/
|
|
12
|
+
import type { ContentBlock } from '@hydraharness/harness-llm';
|
|
13
|
+
import type { SessionEvent } from '@hydraharness/harness-session';
|
|
14
|
+
/**
|
|
15
|
+
* Incremental fold of the selection rule, for backends that observe a child's
|
|
16
|
+
* output as it streams: session-event backends {@link push} each event, and
|
|
17
|
+
* transports without session events (ACP content chunks) {@link pushText} raw
|
|
18
|
+
* text into the same streamed fallback.
|
|
19
|
+
*/
|
|
20
|
+
export declare class AssistantOutputFold {
|
|
21
|
+
private message;
|
|
22
|
+
private partial;
|
|
23
|
+
/**
|
|
24
|
+
* Fold one session event: a non-empty assistant message becomes the
|
|
25
|
+
* candidate final answer, and a `text-delta` chunk extends the streamed
|
|
26
|
+
* fallback; every other event contributes nothing.
|
|
27
|
+
* @param event - the next observed session event.
|
|
28
|
+
*/
|
|
29
|
+
push(event: SessionEvent): void;
|
|
30
|
+
/**
|
|
31
|
+
* Extend the streamed fallback with text observed outside session events.
|
|
32
|
+
* @param text - the next streamed text piece (an empty piece is a no-op).
|
|
33
|
+
*/
|
|
34
|
+
pushText(text: string): void;
|
|
35
|
+
/**
|
|
36
|
+
* Select the final output folded so far.
|
|
37
|
+
* @returns the last non-empty assistant message, else the accumulated
|
|
38
|
+
* streamed text, or `undefined` when the child produced neither.
|
|
39
|
+
*/
|
|
40
|
+
collect(): ContentBlock[] | undefined;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Apply the selection rule to one complete child-owned event suffix.
|
|
44
|
+
* @param events - the child-owned events (after any seed or epoch boundary).
|
|
45
|
+
* @returns the selected output, or `undefined` when the child produced none.
|
|
46
|
+
*/
|
|
47
|
+
export declare function finalAssistantOutput(events: readonly SessionEvent[]): ContentBlock[] | undefined;
|
|
48
|
+
//# sourceMappingURL=assistant-output.d.ts.map
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Canonical selection of a child's final assistant output. Backend run results
|
|
3
|
+
* and `subagent/end.lastAssistantMessage` apply the same rule: select the last
|
|
4
|
+
* non-empty assistant message. An empty-content message records usage only
|
|
5
|
+
* when the loop appends it after a max-tokens step with no executable blocks,
|
|
6
|
+
* so it does not replace earlier output. If no non-empty message exists,
|
|
7
|
+
* select the accumulated assistant text. Selection is independent of the
|
|
8
|
+
* run's stop reason.
|
|
9
|
+
*
|
|
10
|
+
* @module @hydraharness/harness-subagent/assistant-output
|
|
11
|
+
*/
|
|
12
|
+
/**
|
|
13
|
+
* Incremental fold of the selection rule, for backends that observe a child's
|
|
14
|
+
* output as it streams: session-event backends {@link push} each event, and
|
|
15
|
+
* transports without session events (ACP content chunks) {@link pushText} raw
|
|
16
|
+
* text into the same streamed fallback.
|
|
17
|
+
*/
|
|
18
|
+
export class AssistantOutputFold {
|
|
19
|
+
message;
|
|
20
|
+
partial = [];
|
|
21
|
+
/**
|
|
22
|
+
* Fold one session event: a non-empty assistant message becomes the
|
|
23
|
+
* candidate final answer, and a `text-delta` chunk extends the streamed
|
|
24
|
+
* fallback; every other event contributes nothing.
|
|
25
|
+
* @param event - the next observed session event.
|
|
26
|
+
*/
|
|
27
|
+
push(event) {
|
|
28
|
+
if (event.type === 'assistant/message') {
|
|
29
|
+
const content = event.data.message.content;
|
|
30
|
+
if (content.length > 0)
|
|
31
|
+
this.message = content;
|
|
32
|
+
}
|
|
33
|
+
else if (event.type === 'assistant/chunk' && event.data.chunk.type === 'text-delta') {
|
|
34
|
+
this.pushText(event.data.chunk.text);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Extend the streamed fallback with text observed outside session events.
|
|
39
|
+
* @param text - the next streamed text piece (an empty piece is a no-op).
|
|
40
|
+
*/
|
|
41
|
+
pushText(text) {
|
|
42
|
+
if (text.length > 0)
|
|
43
|
+
this.partial.push(text);
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Select the final output folded so far.
|
|
47
|
+
* @returns the last non-empty assistant message, else the accumulated
|
|
48
|
+
* streamed text, or `undefined` when the child produced neither.
|
|
49
|
+
*/
|
|
50
|
+
collect() {
|
|
51
|
+
if (this.message !== undefined)
|
|
52
|
+
return this.message;
|
|
53
|
+
const text = this.partial.join('');
|
|
54
|
+
return text.length > 0 ? [{ type: 'text', text }] : undefined;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Apply the selection rule to one complete child-owned event suffix.
|
|
59
|
+
* @param events - the child-owned events (after any seed or epoch boundary).
|
|
60
|
+
* @returns the selected output, or `undefined` when the child produced none.
|
|
61
|
+
*/
|
|
62
|
+
export function finalAssistantOutput(events) {
|
|
63
|
+
// TODO: this folds the complete suffix once per run/epoch settlement. If a
|
|
64
|
+
// long continuable epoch ever profiles hot here, scan backward with early
|
|
65
|
+
// exit for the last non-empty message and fold text deltas only on the
|
|
66
|
+
// no-message fallback.
|
|
67
|
+
const fold = new AssistantOutputFold();
|
|
68
|
+
for (const event of events)
|
|
69
|
+
fold.push(event);
|
|
70
|
+
return fold.collect();
|
|
71
|
+
}
|
|
72
|
+
//# sourceMappingURL=assistant-output.js.map
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/** Durable delegation admissions and process-local capacity shared by one session tree. */
|
|
2
|
+
import type { Context } from '@hydraharness/cordis';
|
|
3
|
+
import type { Agent } from '@hydraharness/harness-agent';
|
|
4
|
+
import type { Session } from '@hydraharness/harness-session';
|
|
5
|
+
declare module '@hydraharness/harness-session/types' {
|
|
6
|
+
interface SessionEventMap {
|
|
7
|
+
/** One admitted child creation, charged to the delegation root before provider work starts. */
|
|
8
|
+
'subagent/admission': {
|
|
9
|
+
parentId: Session['id'];
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Resolve the live root whose log owns a tree's cumulative budgets.
|
|
15
|
+
* @param ctx - context with the session store.
|
|
16
|
+
* @param agent - current caller.
|
|
17
|
+
* @returns the root session; refuses a detached child whose ancestry cannot be established.
|
|
18
|
+
*/
|
|
19
|
+
export declare function delegationRoot(ctx: Context, agent: Agent): Session;
|
|
20
|
+
/** Tree admission bounds, supplied explicitly by the deployment. */
|
|
21
|
+
export interface DelegationLimits {
|
|
22
|
+
/** Maximum simultaneous child residencies and pending starts per root. */
|
|
23
|
+
maxActivePerTree?: number;
|
|
24
|
+
/** Maximum cumulative child creation attempts per root session, including failed attempts. */
|
|
25
|
+
maxChildrenPerTree?: number;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Reserve capacity before asynchronous setup; a release belongs to the run's settlement.
|
|
29
|
+
* @param ctx - service context.
|
|
30
|
+
* @param limits - optional configured caps.
|
|
31
|
+
* @returns synchronous admission function with an idempotent release.
|
|
32
|
+
*/
|
|
33
|
+
export declare function delegationAdmission(ctx: Context, limits: DelegationLimits): (parent: Agent, creating: boolean) => () => void;
|
|
34
|
+
//# sourceMappingURL=budget.d.ts.map
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { SubagentError } from "./error.js";
|
|
2
|
+
/**
|
|
3
|
+
* Resolve the live root whose log owns a tree's cumulative budgets.
|
|
4
|
+
* @param ctx - context with the session store.
|
|
5
|
+
* @param agent - current caller.
|
|
6
|
+
* @returns the root session; refuses a detached child whose ancestry cannot be established.
|
|
7
|
+
*/
|
|
8
|
+
export function delegationRoot(ctx, agent) {
|
|
9
|
+
let session = agent.session;
|
|
10
|
+
const visited = new Set();
|
|
11
|
+
while (session.header.origin === 'subagent') {
|
|
12
|
+
if (visited.has(session.id))
|
|
13
|
+
throw new SubagentError('cyclic delegation ancestry', 'BUDGET_ANCESTRY_UNAVAILABLE');
|
|
14
|
+
visited.add(session.id);
|
|
15
|
+
const parent = session.header.parentSession === undefined ? undefined : ctx.get('sessions')?.get(session.header.parentSession);
|
|
16
|
+
if (parent === undefined)
|
|
17
|
+
throw new SubagentError('delegation budget requires the live parent session', 'BUDGET_ANCESTRY_UNAVAILABLE');
|
|
18
|
+
session = parent;
|
|
19
|
+
}
|
|
20
|
+
return session;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Reserve capacity before asynchronous setup; a release belongs to the run's settlement.
|
|
24
|
+
* @param ctx - service context.
|
|
25
|
+
* @param limits - optional configured caps.
|
|
26
|
+
* @returns synchronous admission function with an idempotent release.
|
|
27
|
+
*/
|
|
28
|
+
export function delegationAdmission(ctx, limits) {
|
|
29
|
+
for (const value of Object.values(limits)) {
|
|
30
|
+
if (value !== undefined && (!Number.isSafeInteger(value) || value < 1))
|
|
31
|
+
throw new Error('subagent limits must be positive safe integers');
|
|
32
|
+
}
|
|
33
|
+
const active = new WeakMap();
|
|
34
|
+
return (parent, creating) => {
|
|
35
|
+
if (limits.maxActivePerTree === undefined && limits.maxChildrenPerTree === undefined)
|
|
36
|
+
return () => { };
|
|
37
|
+
const root = delegationRoot(ctx, parent);
|
|
38
|
+
const slots = active.get(root) ?? new Set();
|
|
39
|
+
if (limits.maxActivePerTree !== undefined && slots.size >= limits.maxActivePerTree) {
|
|
40
|
+
throw new SubagentError('delegation tree is at its active child limit; wait for a child to settle', 'SUBAGENT_CAPACITY');
|
|
41
|
+
}
|
|
42
|
+
if (creating && limits.maxChildrenPerTree !== undefined) {
|
|
43
|
+
const used = root.events.filter(event => event.type === 'subagent/admission').length;
|
|
44
|
+
if (used >= limits.maxChildrenPerTree)
|
|
45
|
+
throw new SubagentError('delegation tree exhausted its child creation budget', 'SUBAGENT_BUDGET_EXHAUSTED');
|
|
46
|
+
root.append('subagent/admission', { parentId: parent.id });
|
|
47
|
+
}
|
|
48
|
+
const slot = {};
|
|
49
|
+
slots.add(slot);
|
|
50
|
+
active.set(root, slots);
|
|
51
|
+
return () => { slots.delete(slot); };
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
//# sourceMappingURL=budget.js.map
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared in-process child composition: the delegation-depth budget, the
|
|
3
|
+
* durable session metadata, the resolved child `AgentOptions`, the delegated
|
|
4
|
+
* policy seed, and the scoped setup a child agent needs. Both the one-shot
|
|
5
|
+
* provider driver and the continuation manager compose children this way, so
|
|
6
|
+
* depth accounting, lineage stamping, and delegation policy have one home.
|
|
7
|
+
*
|
|
8
|
+
* @module @hydraharness/harness-subagent/child-agent
|
|
9
|
+
*/
|
|
10
|
+
import type { Context } from '@hydraharness/cordis';
|
|
11
|
+
import type { Agent, AgentOptions, CreateAgentOptions } from '@hydraharness/harness-agent';
|
|
12
|
+
import type { SandboxMode } from '@hydraharness/harness-sandbox';
|
|
13
|
+
import type { Session, SessionId } from '@hydraharness/harness-session';
|
|
14
|
+
import type { ToolRestriction } from '@hydraharness/harness-tools';
|
|
15
|
+
/** Thrown when starting a child would exceed the requested depth cap. */
|
|
16
|
+
export declare class SubagentDepthError extends Error {
|
|
17
|
+
readonly attemptedDepth: number;
|
|
18
|
+
readonly maxDepth: number;
|
|
19
|
+
constructor(attemptedDepth: number, maxDepth: number);
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Resolve the child's delegation depth from its parent and enforce an optional
|
|
23
|
+
* cap. The persisted parent header is the monotone floor, so a resumed parent
|
|
24
|
+
* cannot delegate as if it were top-level.
|
|
25
|
+
* @param parent - the delegating parent agent.
|
|
26
|
+
* @param maxDepth - optional absolute cap the resolved depth must not exceed.
|
|
27
|
+
* @returns the child's non-negative safe-integer depth.
|
|
28
|
+
* @throws {SubagentDepthError} when the resolved depth exceeds `maxDepth`.
|
|
29
|
+
* @throws {RangeError} when the resolved depth leaves the safe-integer range.
|
|
30
|
+
*/
|
|
31
|
+
export declare function resolveChildDepth(parent: Agent, maxDepth: number | undefined): number;
|
|
32
|
+
/**
|
|
33
|
+
* Resolve the child's `AgentOptions`: the parent's provider/model/maxTokens
|
|
34
|
+
* route unless the request overrides it, stamped with the child's own
|
|
35
|
+
* delegation depth.
|
|
36
|
+
* @param parent - the delegating parent whose route the child inherits.
|
|
37
|
+
* @param requested - per-child overrides, if any.
|
|
38
|
+
* @param childDepth - the resolved delegation depth to stamp.
|
|
39
|
+
* @returns the resolved options for `ctx.agents.create()`.
|
|
40
|
+
*/
|
|
41
|
+
export declare function resolveChildAgentOptions(parent: Agent, requested: AgentOptions | undefined, childDepth: number): AgentOptions;
|
|
42
|
+
/**
|
|
43
|
+
* Build the child session's durable creation metadata: the parent's workspace,
|
|
44
|
+
* its direct lineage, coarse product origin, the recursion budget that must
|
|
45
|
+
* survive persistence, the seed boundary that separates inherited parent
|
|
46
|
+
* history from child work, and the composition the child runs under.
|
|
47
|
+
*
|
|
48
|
+
* The preset is read from the parent's LIVE scope chain rather than from its
|
|
49
|
+
* header, because a parent that switched preset while blank runs on the newer
|
|
50
|
+
* composition and its header still names the older one. Recording it is what
|
|
51
|
+
* makes a child's history reconstructable: without it a cold read of the child
|
|
52
|
+
* resolves the deployment default and rebuilds turns under a tool set the
|
|
53
|
+
* child never had.
|
|
54
|
+
* @param parent - the delegating parent agent.
|
|
55
|
+
* @param childDepth - the resolved delegation depth to persist.
|
|
56
|
+
* @param lineageSeedLength - how many leading events came from the parent's log.
|
|
57
|
+
* @returns the `meta` for `ctx.agents.create()`.
|
|
58
|
+
*/
|
|
59
|
+
export declare function childSessionMeta(parent: Agent, childDepth: number, lineageSeedLength: number): NonNullable<CreateAgentOptions['meta']>;
|
|
60
|
+
/** The scoped composition a child agent's creation window applies. */
|
|
61
|
+
export interface ChildComposition {
|
|
62
|
+
/** Per-child persona shadowing the deployment persona. */
|
|
63
|
+
readonly persona?: string | undefined;
|
|
64
|
+
/** Per-child tool scoping. */
|
|
65
|
+
readonly toolFilter?: ToolRestriction | undefined;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Model-facing delegation-scope statement for every in-process child. A
|
|
69
|
+
* runtime-context contribution rather than a system-prompt section, so the
|
|
70
|
+
* deployment's system prompt stays uniform across parents and children.
|
|
71
|
+
*/
|
|
72
|
+
export declare const SUBAGENT_DELEGATION_CONTEXT: string;
|
|
73
|
+
/**
|
|
74
|
+
* Compose one child inside its creation window: join its parent's preset,
|
|
75
|
+
* register the fixed delegation-scope statement, then apply the child's own
|
|
76
|
+
* shadowing persona section and tool restriction, all owned by the child's
|
|
77
|
+
* scope and therefore invisible to its parent and siblings. Creation and cold
|
|
78
|
+
* resume both pass through here.
|
|
79
|
+
*
|
|
80
|
+
* The join comes first and the child's own registrations second, which is the
|
|
81
|
+
* order the layering already implies — the nearest scope wins a name, and a
|
|
82
|
+
* per-child restriction intersects with everything its chain admits — but
|
|
83
|
+
* stating it here keeps the two steps from being read as independent.
|
|
84
|
+
*
|
|
85
|
+
* The join and the per-child registrations live in ONE call because a child
|
|
86
|
+
* composed without the join is exactly the defect this function exists to
|
|
87
|
+
* prevent: with every model-facing row on the agent plane, a child that joins
|
|
88
|
+
* no preset sees an empty tool registry and none of its parent's prompt
|
|
89
|
+
* sections. Taking the parent as a parameter is what makes that omission
|
|
90
|
+
* unrepresentable at the call sites.
|
|
91
|
+
* @param childCtx - the child agent's scoped creation context.
|
|
92
|
+
* @param parent - the delegating parent whose composition the child joins.
|
|
93
|
+
* @param composition - the per-child persona and tool filter to install.
|
|
94
|
+
*/
|
|
95
|
+
export declare function applyChildComposition(childCtx: Context, parent: Agent, composition: ChildComposition): void;
|
|
96
|
+
/** Policy seeded onto a child session's log at the delegation boundary. */
|
|
97
|
+
export interface DelegatedPolicyOverrides {
|
|
98
|
+
/** The parent session's explicit sandbox-mode override, or `undefined` without one. */
|
|
99
|
+
readonly sandboxMode: SandboxMode | undefined;
|
|
100
|
+
/**
|
|
101
|
+
* `'never'` whenever the approval capability is composed, `undefined`
|
|
102
|
+
* otherwise: a delegated child acts only within the sandbox scope fixed at
|
|
103
|
+
* delegation, so its asks are rejected deterministically.
|
|
104
|
+
*/
|
|
105
|
+
readonly approvalPolicy: 'never' | undefined;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Capture the policy to seed into one delegation. Call synchronously before
|
|
109
|
+
* the child start's first await: a later parent switch belongs to the
|
|
110
|
+
* parent's future, not to this child. Only the parent session's explicit
|
|
111
|
+
* sandbox override is captured — never deployment defaults or one-shot
|
|
112
|
+
* grants — and the approval policy is pinned to `'never'` regardless of the
|
|
113
|
+
* parent's own policy.
|
|
114
|
+
* @param parent - the delegating parent agent.
|
|
115
|
+
* @returns the sandbox override (or `undefined` without one) and the approval pin.
|
|
116
|
+
*/
|
|
117
|
+
export declare function captureDelegatedPolicyOverrides(parent: Agent): DelegatedPolicyOverrides;
|
|
118
|
+
/**
|
|
119
|
+
* Append the captured delegation policy onto the child's own log as
|
|
120
|
+
* `source: 'delegation'` events inside the unpublished creation window, so the
|
|
121
|
+
* child's effective policy is reconstructable from its log alone. Appends land
|
|
122
|
+
* after any fork seed, so fresh policy wins stale seed state; later child
|
|
123
|
+
* switches still win over these events.
|
|
124
|
+
* @param childSession - the unpublished child's session.
|
|
125
|
+
* @param overrides - the policy captured at delegation.
|
|
126
|
+
*/
|
|
127
|
+
export declare function appendDelegatedPolicyOverrides(childSession: Session, overrides: DelegatedPolicyOverrides): void;
|
|
128
|
+
/** Identity and lineage inputs shared by every in-process child creation. */
|
|
129
|
+
export interface ChildCreateInputs {
|
|
130
|
+
/** The child's reserved session id. */
|
|
131
|
+
readonly sessionId: SessionId;
|
|
132
|
+
/** The delegating parent agent. */
|
|
133
|
+
readonly parent: Agent;
|
|
134
|
+
/** The resolved delegation depth. */
|
|
135
|
+
readonly childDepth: number;
|
|
136
|
+
/** How many leading seed events came from the parent's log. */
|
|
137
|
+
readonly lineageSeedLength: number;
|
|
138
|
+
}
|
|
139
|
+
//# sourceMappingURL=child-agent.d.ts.map
|