dsh-harness-reflex 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -6
- package/client.js +3511 -185
- package/dist/attribution.d.ts +266 -0
- package/dist/attribution.js +238 -0
- package/dist/attribution.js.map +1 -0
- package/dist/bridge.d.ts +311 -13
- package/dist/bridge.js +714 -42
- package/dist/bridge.js.map +1 -1
- package/dist/client-bundle.js +4 -1
- package/dist/client-bundle.js.map +1 -1
- package/dist/command.js +10 -0
- package/dist/command.js.map +1 -1
- package/dist/config.d.ts +530 -22
- package/dist/config.js +808 -27
- package/dist/config.js.map +1 -1
- package/dist/delegation-dispatch.d.ts +132 -0
- package/dist/delegation-dispatch.js +186 -0
- package/dist/delegation-dispatch.js.map +1 -0
- package/dist/delegation-health.d.ts +131 -0
- package/dist/delegation-health.js +97 -0
- package/dist/delegation-health.js.map +1 -0
- package/dist/delegation.d.ts +148 -0
- package/dist/delegation.js +186 -0
- package/dist/delegation.js.map +1 -0
- package/dist/effort-delegation.d.ts +144 -0
- package/dist/effort-delegation.js +280 -0
- package/dist/effort-delegation.js.map +1 -0
- package/dist/effort.d.ts +141 -0
- package/dist/effort.js +251 -9
- package/dist/effort.js.map +1 -1
- package/dist/host-patch.d.ts +156 -0
- package/dist/host-patch.js +534 -0
- package/dist/host-patch.js.map +1 -0
- package/dist/index.d.ts +12 -3
- package/dist/index.js +99 -7
- package/dist/index.js.map +1 -1
- package/dist/interventions.d.ts +98 -373
- package/dist/interventions.js +442 -1702
- package/dist/interventions.js.map +1 -1
- package/dist/panel-api.d.ts +328 -4
- package/dist/panel-api.js +322 -15
- package/dist/panel-api.js.map +1 -1
- package/dist/panel-mount.d.ts +81 -22
- package/dist/panel-mount.js +228 -7
- package/dist/panel-mount.js.map +1 -1
- package/dist/routing.d.ts +23 -18
- package/dist/routing.js +471 -153
- package/dist/routing.js.map +1 -1
- package/dist/session-audit.d.ts +70 -0
- package/dist/session-audit.js +73 -0
- package/dist/session-audit.js.map +1 -1
- package/dist/systemone-probe.d.ts +114 -0
- package/dist/systemone-probe.js +383 -0
- package/dist/systemone-probe.js.map +1 -0
- package/dist/testing.d.ts +212 -7
- package/dist/testing.js +333 -27
- package/dist/testing.js.map +1 -1
- package/dist/tools.d.ts +109 -3
- package/dist/tools.js +103 -4
- package/dist/tools.js.map +1 -1
- package/dist/unconfigured-backend.d.ts +72 -0
- package/dist/unconfigured-backend.js +94 -0
- package/dist/unconfigured-backend.js.map +1 -0
- package/dist/vendor/harness-reflex/backend/factory.d.ts +31 -1
- package/dist/vendor/harness-reflex/backend/factory.js +18 -3
- package/dist/vendor/harness-reflex/backend/factory.js.map +1 -1
- package/dist/vendor/harness-reflex/backend/jev.d.ts +20 -0
- package/dist/vendor/harness-reflex/backend/jev.js +11 -4
- package/dist/vendor/harness-reflex/backend/jev.js.map +1 -1
- package/dist/vendor/harness-reflex/backend/simple-jev.d.ts +16 -0
- package/dist/vendor/harness-reflex/backend/simple-jev.js +17 -6
- package/dist/vendor/harness-reflex/backend/simple-jev.js.map +1 -1
- package/dist/vendor/harness-reflex/core/closing.d.ts +90 -0
- package/dist/vendor/harness-reflex/core/closing.js +111 -0
- package/dist/vendor/harness-reflex/core/closing.js.map +1 -0
- package/dist/vendor/harness-reflex/core/evidence.d.ts +119 -0
- package/dist/vendor/harness-reflex/core/evidence.js +209 -0
- package/dist/vendor/harness-reflex/core/evidence.js.map +1 -0
- package/dist/vendor/harness-reflex/core/judge.d.ts +221 -0
- package/dist/vendor/harness-reflex/core/judge.js +251 -0
- package/dist/vendor/harness-reflex/core/judge.js.map +1 -0
- package/dist/vendor/harness-reflex/core/orchestrate-closing.d.ts +237 -0
- package/dist/vendor/harness-reflex/core/orchestrate-closing.js +250 -0
- package/dist/vendor/harness-reflex/core/orchestrate-closing.js.map +1 -0
- package/dist/vendor/harness-reflex/core/orchestrate-correction.d.ts +209 -0
- package/dist/vendor/harness-reflex/core/orchestrate-correction.js +141 -0
- package/dist/vendor/harness-reflex/core/orchestrate-correction.js.map +1 -0
- package/dist/vendor/harness-reflex/core/orchestrate-host.d.ts +225 -0
- package/dist/vendor/harness-reflex/core/orchestrate-host.js +80 -0
- package/dist/vendor/harness-reflex/core/orchestrate-host.js.map +1 -0
- package/dist/vendor/harness-reflex/core/orchestrate-stagnation.d.ts +259 -0
- package/dist/vendor/harness-reflex/core/orchestrate-stagnation.js +270 -0
- package/dist/vendor/harness-reflex/core/orchestrate-stagnation.js.map +1 -0
- package/dist/vendor/harness-reflex/core/orchestrate.d.ts +357 -0
- package/dist/vendor/harness-reflex/core/orchestrate.js +418 -0
- package/dist/vendor/harness-reflex/core/orchestrate.js.map +1 -0
- package/dist/vendor/harness-reflex/core/policy.d.ts +122 -0
- package/dist/vendor/harness-reflex/core/policy.js +102 -0
- package/dist/vendor/harness-reflex/core/policy.js.map +1 -0
- package/dist/vendor/harness-reflex/core/prune-plan.d.ts +141 -0
- package/dist/vendor/harness-reflex/core/prune-plan.js +390 -0
- package/dist/vendor/harness-reflex/core/prune-plan.js.map +1 -0
- package/dist/vendor/harness-reflex/core/text.d.ts +36 -0
- package/dist/vendor/harness-reflex/core/text.js +66 -0
- package/dist/vendor/harness-reflex/core/text.js.map +1 -0
- package/dist/vendor/harness-reflex/ports/audit.d.ts +18 -0
- package/dist/vendor/harness-reflex/ports/audit.js +11 -0
- package/dist/vendor/harness-reflex/ports/audit.js.map +1 -0
- package/dist/vendor/harness-reflex/ports/clock.d.ts +14 -0
- package/dist/vendor/harness-reflex/ports/clock.js +11 -0
- package/dist/vendor/harness-reflex/ports/clock.js.map +1 -0
- package/dist/vendor/harness-reflex/ports/decision.d.ts +75 -0
- package/dist/vendor/harness-reflex/ports/decision.js +2 -0
- package/dist/vendor/harness-reflex/ports/decision.js.map +1 -0
- package/dist/vendor/harness-reflex/ports/index.d.ts +14 -0
- package/dist/vendor/harness-reflex/ports/index.js +2 -0
- package/dist/vendor/harness-reflex/ports/index.js.map +1 -0
- package/dist/vendor/harness-reflex/ports/log.d.ts +22 -0
- package/dist/vendor/harness-reflex/ports/log.js +12 -0
- package/dist/vendor/harness-reflex/ports/log.js.map +1 -0
- package/dist/vendor/harness-reflex/ports/state.d.ts +46 -0
- package/dist/vendor/harness-reflex/ports/state.js +13 -0
- package/dist/vendor/harness-reflex/ports/state.js.map +1 -0
- package/package.json +25 -13
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import { EFFORT_AUDIT_TASK_CHARS, EFFORT_CHOICE_OPTIONS, levelOfChoiceOption } from './effort.js';
|
|
2
|
+
/**
|
|
3
|
+
* The levels a delegation may carry.
|
|
4
|
+
*
|
|
5
|
+
* `off`, `minimal`, and `max` are intentionally absent: the DSH tool's own
|
|
6
|
+
* `reasoning_effort` accepts a `low`/`medium`/`high` vocabulary, and accepting a
|
|
7
|
+
* level the transport cannot express would force this layer to silently invent
|
|
8
|
+
* a replacement — the second decision layer the goal forbids.
|
|
9
|
+
*/
|
|
10
|
+
export const DELEGATION_EFFORT_LEVELS = ['low', 'medium', 'high'];
|
|
11
|
+
/**
|
|
12
|
+
* Levels offered to System One, narrowest first.
|
|
13
|
+
*
|
|
14
|
+
* Three candidates is what makes the confidence floor meaningful: with two, a
|
|
15
|
+
* uniform backend would answer `0.5`, which no simple "above one half" rule
|
|
16
|
+
* separates from a real lean. The vendor descriptions (see
|
|
17
|
+
* {@link EFFORT_CHOICE_OPTIONS}) are kept verbatim so the delegated decision
|
|
18
|
+
* speaks the same scenario vocabulary as the per-turn one.
|
|
19
|
+
*/
|
|
20
|
+
export const DELEGATION_CHOICE_OPTIONS = EFFORT_CHOICE_OPTIONS.filter((option) => {
|
|
21
|
+
const level = levelOfChoiceOption(option);
|
|
22
|
+
return level !== undefined && DELEGATION_EFFORT_LEVELS.includes(level);
|
|
23
|
+
});
|
|
24
|
+
/**
|
|
25
|
+
* Build the System One question for one delegation.
|
|
26
|
+
*
|
|
27
|
+
* The description leads because it is the caller's own summary of the task, and
|
|
28
|
+
* the prompt body follows, truncated. Neither is rewritten: unlike a turn input,
|
|
29
|
+
* a delegated task is work to be done, not an instruction that might be quoted
|
|
30
|
+
* back, so the P9 restatement cleanup does not apply here.
|
|
31
|
+
* @param description - short task label.
|
|
32
|
+
* @param prompt - task body.
|
|
33
|
+
* @returns the question text.
|
|
34
|
+
*/
|
|
35
|
+
export function buildDelegationQuestion(description, prompt) {
|
|
36
|
+
const head = description.trim();
|
|
37
|
+
const body = prompt.trim();
|
|
38
|
+
const parts = [head, body].filter((part) => part.length > 0);
|
|
39
|
+
return parts.join('\n\n').slice(0, EFFORT_AUDIT_TASK_CHARS * 4);
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Map any effort id onto the delegation vocabulary by rank.
|
|
43
|
+
* @param effort - an effort id the parent may carry (`low`, `minimal`, `xhigh`, …).
|
|
44
|
+
* @returns the nearest delegation level, or `undefined` when it names none.
|
|
45
|
+
*/
|
|
46
|
+
export function toDelegationEffort(effort) {
|
|
47
|
+
if (effort === undefined)
|
|
48
|
+
return undefined;
|
|
49
|
+
const normalized = effort.trim().toLowerCase();
|
|
50
|
+
if (normalized === 'off')
|
|
51
|
+
return undefined;
|
|
52
|
+
if (normalized === 'minimal' || normalized === 'low' || normalized === 'medium') {
|
|
53
|
+
return normalized === 'minimal' ? 'low' : normalized;
|
|
54
|
+
}
|
|
55
|
+
// `high`, `xhigh`, `max`, and anything else the host may add all land on the
|
|
56
|
+
// deepest level the transport can express.
|
|
57
|
+
return 'high';
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Decide the reasoning level for one delegation.
|
|
61
|
+
*
|
|
62
|
+
* The chain is: System One → trust check → fallback. It never throws, because a
|
|
63
|
+
* delegation whose level could not be decided must still be delegatable.
|
|
64
|
+
*
|
|
65
|
+
* The trust check has two parts, and both are needed for the same reason: a
|
|
66
|
+
* confidence number alone is not evidence. An answer that merely ties the
|
|
67
|
+
* uniform baseline (`1 / candidates`) carries no information at all — the
|
|
68
|
+
* winner is then whichever option came first — and an answer below the
|
|
69
|
+
* deployment's floor is too weak to act on. Either way the parent's own level
|
|
70
|
+
* is inherited instead of invented, so a weak signal can never silently change
|
|
71
|
+
* how deeply a child thinks.
|
|
72
|
+
* @param options - task text, System One seam, floor, and parent facts.
|
|
73
|
+
* @returns the decision, with the reason recorded when it degraded.
|
|
74
|
+
*/
|
|
75
|
+
export async function decideDelegationEffort(options) {
|
|
76
|
+
const now = options.now ?? (() => performance.now());
|
|
77
|
+
const started = now();
|
|
78
|
+
const inherited = inheritParentEffort(options.parent);
|
|
79
|
+
let response;
|
|
80
|
+
try {
|
|
81
|
+
response = await options.decide({
|
|
82
|
+
question: buildDelegationQuestion(options.description, options.prompt),
|
|
83
|
+
options: [...DELEGATION_CHOICE_OPTIONS],
|
|
84
|
+
context: 'the work this delegated subagent has to finish; choose the reasoning depth it needs'
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
catch (error) {
|
|
88
|
+
return degraded(inherited, `system-one call failed: ${errorMessage(error)}`, started, now);
|
|
89
|
+
}
|
|
90
|
+
const option = String(response?.bestOption ?? '');
|
|
91
|
+
const level = levelOfChoiceOption(option);
|
|
92
|
+
if (level === undefined || !DELEGATION_EFFORT_LEVELS.includes(level)) {
|
|
93
|
+
return degraded(inherited, `system-one answered with an unknown option: ${option.slice(0, 40) || '(empty)'}`, started, now);
|
|
94
|
+
}
|
|
95
|
+
const confidence = Number(response?.confidence);
|
|
96
|
+
if (!Number.isFinite(confidence)) {
|
|
97
|
+
return degraded(inherited, `system-one answered without a confidence: ${option.slice(0, 40)}`, started, now);
|
|
98
|
+
}
|
|
99
|
+
const uniform = 1 / DELEGATION_CHOICE_OPTIONS.length;
|
|
100
|
+
if (confidence <= uniform) {
|
|
101
|
+
return degraded(inherited, `system-one confidence ${confidence.toFixed(2)} does not beat the ${DELEGATION_CHOICE_OPTIONS.length}-way baseline ${uniform.toFixed(2)}`, started, now);
|
|
102
|
+
}
|
|
103
|
+
if (confidence < options.minConfidence) {
|
|
104
|
+
return degraded(inherited, `system-one confidence ${confidence.toFixed(2)} is below the floor ${options.minConfidence.toFixed(2)}`, started, now);
|
|
105
|
+
}
|
|
106
|
+
return {
|
|
107
|
+
level: level,
|
|
108
|
+
source: 'system-one',
|
|
109
|
+
confidence,
|
|
110
|
+
latencyMs: elapsed(now(), started),
|
|
111
|
+
basis: [option.trim().split(/\s+/, 1)[0] ?? level]
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* The level a delegation inherits when System One cannot be trusted.
|
|
116
|
+
*
|
|
117
|
+
* The parent's own effort is honoured rather than reset: a parent already
|
|
118
|
+
* thinking at `high` does not hand a `medium` child the work it was made for.
|
|
119
|
+
* A parent with no reasoning at all (or one at `off`) falls to `medium`, the
|
|
120
|
+
* vendor default for "no evidence either way".
|
|
121
|
+
* @param parent - parent facts.
|
|
122
|
+
* @returns the inherited level.
|
|
123
|
+
*/
|
|
124
|
+
export function inheritParentEffort(parent) {
|
|
125
|
+
return toDelegationEffort(parent.reasoningEffort) ?? 'medium';
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Record one delegation level in the audit ledger.
|
|
129
|
+
*
|
|
130
|
+
* It lands in the same ledger as the per-turn decisions, tagged `kind:
|
|
131
|
+
* 'delegation'` and attributed to the `reflex-delegate` backend, so
|
|
132
|
+
* `/reflex-ledger` and the ledger summary separate the two without a second
|
|
133
|
+
* sink to configure.
|
|
134
|
+
* @param ledger - the activation's ledger.
|
|
135
|
+
* @param decision - the decided level.
|
|
136
|
+
* @param args - the model-facing arguments, for attribution.
|
|
137
|
+
* @param parent - parent facts, for attribution.
|
|
138
|
+
*/
|
|
139
|
+
export function recordDelegationDecision(ledger, decision, args, parent) {
|
|
140
|
+
try {
|
|
141
|
+
ledger.record({
|
|
142
|
+
type: 'effort-decision',
|
|
143
|
+
backend: 'reflex-delegate',
|
|
144
|
+
latencyMs: decision.latencyMs,
|
|
145
|
+
details: {
|
|
146
|
+
goal: args.description.trim().slice(0, EFFORT_AUDIT_TASK_CHARS) || '(no description)',
|
|
147
|
+
kind: 'delegation',
|
|
148
|
+
level: decision.level,
|
|
149
|
+
applied: decision.level,
|
|
150
|
+
source: decision.source,
|
|
151
|
+
confidence: decision.confidence,
|
|
152
|
+
basis: decision.basis,
|
|
153
|
+
...(args.provider === undefined ? {} : { provider: args.provider }),
|
|
154
|
+
...(args.model === undefined ? {} : { model: args.model }),
|
|
155
|
+
...(parent.reasoningEffort === undefined ? {} : { parentEffort: parent.reasoningEffort }),
|
|
156
|
+
...(parent.model === undefined ? {} : { parentModel: parent.model }),
|
|
157
|
+
...(decision.degradedReason ? { degraded: decision.degradedReason } : {})
|
|
158
|
+
}
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
catch {
|
|
162
|
+
// The ledger is an audit sink; losing an entry must never fail a delegation.
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
/** Compose a degraded decision on the inherited level. */
|
|
166
|
+
function degraded(level, reason, started, now) {
|
|
167
|
+
return {
|
|
168
|
+
level,
|
|
169
|
+
source: 'inherited',
|
|
170
|
+
confidence: 0,
|
|
171
|
+
latencyMs: elapsed(now(), started),
|
|
172
|
+
basis: [`inherited ${level}`],
|
|
173
|
+
degradedReason: reason
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
/** Short, single-line rendering of a caught value. */
|
|
177
|
+
function errorMessage(error) {
|
|
178
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
179
|
+
return message.split('\n', 1)[0]?.slice(0, 120) || 'unknown error';
|
|
180
|
+
}
|
|
181
|
+
/** Milliseconds since a monotonic start, never negative. */
|
|
182
|
+
function elapsed(now, started) {
|
|
183
|
+
const delta = now - started;
|
|
184
|
+
return Number.isFinite(delta) && delta > 0 ? Math.round(delta) : 0;
|
|
185
|
+
}
|
|
186
|
+
//# sourceMappingURL=delegation.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"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flex/backend/types.js';\nimport type { DecisionLedger } from './vendor/harness-reflex/core/ledger.js';\nimport {\n EFFORT_AUDIT_TASK_CHARS,\n EFFORT_CHOICE_OPTIONS,\n levelOfChoiceOption,\n type AdaptiveEffortLevel\n} from './effort.js';\n\n/**\n * One System One judgement spent on \"how deep should this delegated task be\n * thought through\", before the task is handed to the DSH `subagent` tool.\n *\n * Only the reasoning level is decided here. The caller's `provider`/`model` are\n * passed straight through to the Host tool and are *not* validated in this\n * module: the Host's `assertAllowedModelSelection` owns that policy, and\n * duplicating it would be the second decision layer the goal forbids.\n *\n * @module dsh-reflex/delegation\n */\n\n/** The model-facing arguments of `reflex_delegate`, in declaration order. */\nexport interface ReflexDelegateArgs {\n /** The task handed to the child agent. */\n prompt: string;\n /** Short display label for the delegated task. */\n description: string;\n /** Child LLM provider id; passed straight through to the DSH tool. */\n provider?: string;\n /** Exact model id within that provider; passed straight through. */\n model?: string;\n /** Initial child working directory; passed straight through. */\n cwd?: string;\n}\n\n/** The `reasoning_effort` vocabulary the DSH `subagent` tool declares. */\nexport type DelegationEffort = 'low' | 'medium' | 'high';\n\n/**\n * The levels a delegation may carry.\n *\n * `off`, `minimal`, and `max` are intentionally absent: the DSH tool's own\n * `reasoning_effort` accepts a `low`/`medium`/`high` vocabulary, and accepting a\n * level the transport cannot express would force this layer to silently invent\n * a replacement — the second decision layer the goal forbids.\n */\nexport const DELEGATION_EFFORT_LEVELS: readonly DelegationEffort[] = ['low', 'medium', 'high'];\n\n/**\n * Levels offered to System One, narrowest first.\n *\n * Three candidates is what makes the confidence floor meaningful: with two, a\n * uniform backend would answer `0.5`, which no simple \"above one half\" rule\n * separates from a real lean. The vendor descriptions (see\n * {@link EFFORT_CHOICE_OPTIONS}) are kept verbatim so the delegated decision\n * speaks the same scenario vocabulary as the per-turn one.\n */\nexport const DELEGATION_CHOICE_OPTIONS: readonly string[] = EFFORT_CHOICE_OPTIONS.filter((option) => {\n const level = levelOfChoiceOption(option);\n return level !== undefined && (DELEGATION_EFFORT_LEVELS as readonly string[]).includes(level);\n});\n\n/** How one delegation's level was reached, for the audit record. */\nexport type DelegationSource = 'system-one' | 'inherited';\n\n/** Facts about the parent session that the fallback inherits from. */\nexport interface DelegationParentFacts {\n /** Parent's negotiated reasoning effort, when it has one. */\n readonly reasoningEffort?: string;\n /** Parent's model id, when it has one. */\n readonly model?: string;\n}\n\n/** The resolved delegation level plus everything needed to audit it. */\nexport interface DelegationDecision {\n /** The `low`/`medium`/`high` value handed to the DSH tool. */\n level: DelegationEffort;\n /** Whether System One decided it, or the parent's own effort was inherited. */\n source: DelegationSource;\n /** Confidence of the winning option; `0` for an inherited level. */\n confidence: number;\n /** Wall-clock milliseconds spent deciding. */\n latencyMs: number;\n /** Verbatim evidence the decision rested on. */\n basis: string[];\n /** Set when System One was unavailable, untrusted, or disagreed with itself. */\n degradedReason?: string;\n}\n\n/** Options of {@link decideDelegationEffort}. */\nexport interface DelegationDecisionOptions {\n /** Model-facing task text; the judgement's question. */\n readonly description: string;\n /** Model-facing task body; appended to the question. */\n readonly prompt: string;\n /** System One choice execution. */\n readonly decide: (request: ChoiceRequest) => Promise<{ bestOption?: unknown; confidence?: unknown }>;\n /** Minimum confidence for a System One answer to be trusted. */\n readonly minConfidence: number;\n /** Parent facts the fallback inherits from. */\n readonly parent: DelegationParentFacts;\n /** Monotonic clock, injectable for tests. */\n readonly now?: () => number;\n}\n\n/**\n * Build the System One question for one delegation.\n *\n * The description leads because it is the caller's own summary of the task, and\n * the prompt body follows, truncated. Neither is rewritten: unlike a turn input,\n * a delegated task is work to be done, not an instruction that might be quoted\n * back, so the P9 restatement cleanup does not apply here.\n * @param description - short task label.\n * @param prompt - task body.\n * @returns the question text.\n */\nexport function buildDelegationQuestion(description: string, prompt: string): string {\n const head = description.trim();\n const body = prompt.trim();\n const parts = [head, body].filter((part) => part.length > 0);\n return parts.join('\\n\\n').slice(0, EFFORT_AUDIT_TASK_CHARS * 4);\n}\n\n/**\n * Map any effort id onto the delegation vocabulary by rank.\n * @param effort - an effort id the parent may carry (`low`, `minimal`, `xhigh`, …).\n * @returns the nearest delegation level, or `undefined` when it names none.\n */\nexport function toDelegationEffort(effort: string | undefined): DelegationEffort | undefined {\n if (effort === undefined) return undefined;\n const normalized = effort.trim().toLowerCase();\n if (normalized === 'off') return undefined;\n if (normalized === 'minimal' || normalized === 'low' || normalized === 'medium') {\n return normalized === 'minimal' ? 'low' : (normalized as DelegationEffort);\n }\n // `high`, `xhigh`, `max`, and anything else the host may add all land on the\n // deepest level the transport can express.\n return 'high';\n}\n\n/**\n * Decide the reasoning level for one delegation.\n *\n * The chain is: System One → trust check → fallback. It never throws, because a\n * delegation whose level could not be decided must still be delegatable.\n *\n * The trust check has two parts, and both are needed for the same reason: a\n * confidence number alone is not evidence. An answer that merely ties the\n * uniform baseline (`1 / candidates`) carries no information at all — the\n * winner is then whichever option came first — and an answer below the\n * deployment's floor is too weak to act on. Either way the parent's own level\n * is inherited instead of invented, so a weak signal can never silently change\n * how deeply a child thinks.\n * @param options - task text, System One seam, floor, and parent facts.\n * @returns the decision, with the reason recorded when it degraded.\n */\nexport async function decideDelegationEffort(options: DelegationDecisionOptions): Promise<DelegationDecision> {\n const now = options.now ?? (() => performance.now());\n const started = now();\n const inherited = inheritParentEffort(options.parent);\n\n let response: { bestOption?: unknown; confidence?: unknown };\n try {\n response = await options.decide({\n question: buildDelegationQuestion(options.description, options.prompt),\n options: [...DELEGATION_CHOICE_OPTIONS],\n context: 'the work this delegated subagent has to finish; choose the reasoning depth it needs'\n });\n } catch (error) {\n return degraded(inherited, `system-one call failed: ${errorMessage(error)}`, started, now);\n }\n\n const option = String(response?.bestOption ?? '');\n const level = levelOfChoiceOption(option);\n if (level === undefined || !(DELEGATION_EFFORT_LEVELS as readonly string[]).includes(level)) {\n return degraded(inherited, `system-one answered with an unknown option: ${option.slice(0, 40) || '(empty)'}`, started, now);\n }\n\n const confidence = Number(response?.confidence);\n if (!Number.isFinite(confidence)) {\n return degraded(inherited, `system-one answered without a confidence: ${option.slice(0, 40)}`, started, now);\n }\n\n const uniform = 1 / DELEGATION_CHOICE_OPTIONS.length;\n if (confidence <= uniform) {\n return degraded(\n inherited,\n `system-one confidence ${confidence.toFixed(2)} does not beat the ${DELEGATION_CHOICE_OPTIONS.length}-way baseline ${uniform.toFixed(2)}`,\n started,\n now\n );\n }\n if (confidence < options.minConfidence) {\n return degraded(\n inherited,\n `system-one confidence ${confidence.toFixed(2)} is below the floor ${options.minConfidence.toFixed(2)}`,\n started,\n now\n );\n }\n\n return {\n level: level as DelegationEffort,\n source: 'system-one',\n confidence,\n latencyMs: elapsed(now(), started),\n basis: [option.trim().split(/\\s+/, 1)[0] ?? level]\n };\n}\n\n/**\n * The level a delegation inherits when System One cannot be trusted.\n *\n * The parent's own effort is honoured rather than reset: a parent already\n * thinking at `high` does not hand a `medium` child the work it was made for.\n * A parent with no reasoning at all (or one at `off`) falls to `medium`, the\n * vendor default for \"no evidence either way\".\n * @param parent - parent facts.\n * @returns the inherited level.\n */\nexport function inheritParentEffort(parent: DelegationParentFacts): DelegationEffort {\n return toDelegationEffort(parent.reasoningEffort) ?? 'medium';\n}\n\n/**\n * Record one delegation level in the audit ledger.\n *\n * It lands in the same ledger as the per-turn decisions, tagged `kind:\n * 'delegation'` and attributed to the `reflex-delegate` backend, so\n * `/reflex-ledger` and the ledger summary separate the two without a second\n * sink to configure.\n * @param ledger - the activation's ledger.\n * @param decision - the decided level.\n * @param args - the model-facing arguments, for attribution.\n * @param parent - parent facts, for attribution.\n */\nexport function recordDelegationDecision(\n ledger: DecisionLedger,\n decision: DelegationDecision,\n args: ReflexDelegateArgs,\n parent: DelegationParentFacts\n): void {\n try {\n ledger.record({\n type: 'effort-decision',\n backend: 'reflex-delegate',\n latencyMs: decision.latencyMs,\n details: {\n goal: args.description.trim().slice(0, EFFORT_AUDIT_TASK_CHARS) || '(no description)',\n kind: 'delegation',\n level: decision.level,\n applied: decision.level,\n source: decision.source,\n confidence: decision.confidence,\n basis: decision.basis,\n ...(args.provider === undefined ? {} : { provider: args.provider }),\n ...(args.model === undefined ? {} : { model: args.model }),\n ...(parent.reasoningEffort === undefined ? {} : { parentEffort: parent.reasoningEffort }),\n ...(parent.model === undefined ? {} : { parentModel: parent.model }),\n ...(decision.degradedReason ? { degraded: decision.degradedReason } : {})\n }\n });\n } catch {\n // The ledger is an audit sink; losing an entry must never fail a delegation.\n }\n}\n\n/** Compose a degraded decision on the inherited level. */\nfunction degraded(\n level: DelegationEffort,\n reason: string,\n started: number,\n now: () => number\n): DelegationDecision {\n return {\n level,\n source: 'inherited',\n confidence: 0,\n latencyMs: elapsed(now(), started),\n basis: [`inherited ${level}`],\n degradedReason: reason\n };\n}\n\n/** Short, single-line rendering of a caught value. */\nfunction errorMessage(error: unknown): string {\n const message = error instanceof Error ? error.message : String(error);\n return message.split('\\n', 1)[0]?.slice(0, 120) || 'unknown error';\n}\n\n/** Milliseconds since a monotonic start, never negative. */\nfunction elapsed(now: number, started: number): number {\n const delta = now - started;\n return Number.isFinite(delta) && delta > 0 ? Math.round(delta) : 0;\n}\n"]}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import type { Context } from '@deepseek-ai/cordis';
|
|
2
|
+
/**
|
|
3
|
+
* Delegated agents cannot decide their own reasoning effort — so let them inherit.
|
|
4
|
+
*
|
|
5
|
+
* ## Why this exists (g-048)
|
|
6
|
+
*
|
|
7
|
+
* `executor.reasoning_effort: "reflex"` marks a deployment as adaptive: the
|
|
8
|
+
* plugin decides the level per turn. For a delegated agent that decision used to
|
|
9
|
+
* be taken inside the `agent/request` waterfall, and `dsh-agent-loop` refuses
|
|
10
|
+
* exactly that — it fixes the step's effort during step preparation and rejects
|
|
11
|
+
* any later proposal:
|
|
12
|
+
*
|
|
13
|
+
* agent/request proposed reasoning effort "low" after step preparation fixed
|
|
14
|
+
* "reflex"; use agent.model.select() before step preparation
|
|
15
|
+
*
|
|
16
|
+
* The waterfall may re-route a request; it may not re-decide the effort. And
|
|
17
|
+
* `agent/pre-step` cannot help either: the loop reads `model.current()` for that
|
|
18
|
+
* step *before* the waterfall runs, so a `modelSelection` handed back from
|
|
19
|
+
* `pre-step` is already too late. There is no host hook between "the selection is
|
|
20
|
+
* recorded" and "the step reads it".
|
|
21
|
+
*
|
|
22
|
+
* ## What this does instead (C1)
|
|
23
|
+
*
|
|
24
|
+
* The marker the delegated agent would have decided on is replaced on its own
|
|
25
|
+
* `model/selection` — the very log entry the loop folds to obtain `model.current()`
|
|
26
|
+
* — with the level its parent session is currently using. The step then fixes a
|
|
27
|
+
* concrete level, the request waterfall has nothing left to change, and the loop's
|
|
28
|
+
* contract holds by construction rather than by suppressing a check.
|
|
29
|
+
*
|
|
30
|
+
* ## Why the rewrite is a second `model/selection` event
|
|
31
|
+
*
|
|
32
|
+
* The arriving event is deep-frozen (the Session snapshots and freezes every
|
|
33
|
+
* payload) and the append that published it is still on the stack, so a listener
|
|
34
|
+
* cannot rewrite it in place: `session append cannot reenter while another append
|
|
35
|
+
* is being published`. Returning *before* the projection folds is not an option
|
|
36
|
+
* either — listeners run in registration order, and the projection that serves
|
|
37
|
+
* `model.current()` is registered by the agent runtime, ahead of this plugin.
|
|
38
|
+
*
|
|
39
|
+
* So the rewrite is committed immediately *after* the current append completes,
|
|
40
|
+
* as one further `model/selection`. Only the last one counts: the selection fold
|
|
41
|
+
* takes `pending` from the newest `model/selection`, which is exactly the value
|
|
42
|
+
* `model.current()` returns. Nothing reads the selection in between — the driver
|
|
43
|
+
* reaches its next step only after the current one has fully committed.
|
|
44
|
+
*
|
|
45
|
+
* Deferring also buys the ordering the parent needs. A child's selection may be
|
|
46
|
+
* recorded before the parent has one, and the parent's own level may change
|
|
47
|
+
* later; settling on a microtask keeps the copy current without depending on
|
|
48
|
+
* which session was configured first.
|
|
49
|
+
*
|
|
50
|
+
* ## Boundaries
|
|
51
|
+
*
|
|
52
|
+
* - **Only delegated sessions.** A `delegationDepth > 0` header or a `subagent`
|
|
53
|
+
* origin marks one; a main session is never touched, so the adaptive behaviour
|
|
54
|
+
* its deployment asked for is bit-for-bit unchanged.
|
|
55
|
+
* - **Only the marker.** `reflex`/`auto` is rewritten. A concrete level — the
|
|
56
|
+
* caller's own choice — is left exactly as recorded.
|
|
57
|
+
* - **`effort.enabled: false` keeps today's behaviour**, i.e. nothing happens
|
|
58
|
+
* here and the interceptor clears the marker later, landing on the adapter's
|
|
59
|
+
* default. Inheriting the parent's level would silently change what a switched
|
|
60
|
+
* off deployment does.
|
|
61
|
+
* - **No parent level, no inheritance:** the marker is removed, which is the
|
|
62
|
+
* adapter's own default — the same outcome the disabled switch has, reached for
|
|
63
|
+
* a different reason (recorded as such).
|
|
64
|
+
*
|
|
65
|
+
* @module dsh-reflex/effort-delegation
|
|
66
|
+
*/
|
|
67
|
+
/** The only reason this module rewrites anything. */
|
|
68
|
+
export declare const DELEGATION_EFFORT_REASON: "subagent-cannot-decide";
|
|
69
|
+
/** Structural view of the session header fields delegation is decided on. */
|
|
70
|
+
interface SessionHeaderLike {
|
|
71
|
+
origin?: string;
|
|
72
|
+
delegationDepth?: number;
|
|
73
|
+
parentSession?: unknown;
|
|
74
|
+
}
|
|
75
|
+
/** Structural view of the selection events this module reads and writes. */
|
|
76
|
+
interface SelectionData {
|
|
77
|
+
provider: string;
|
|
78
|
+
model: string;
|
|
79
|
+
reasoningEffort?: string;
|
|
80
|
+
}
|
|
81
|
+
/** Structural view of a live session. */
|
|
82
|
+
interface SessionLike {
|
|
83
|
+
readonly id?: string;
|
|
84
|
+
readonly header?: SessionHeaderLike;
|
|
85
|
+
append(type: string, data: unknown): unknown;
|
|
86
|
+
snapshotEvents?(): readonly {
|
|
87
|
+
type: string;
|
|
88
|
+
data?: any;
|
|
89
|
+
}[];
|
|
90
|
+
}
|
|
91
|
+
/** What {@link installDelegatedEffortInheritance} needs from the activation. */
|
|
92
|
+
export interface DelegatedEffortInheritanceOptions {
|
|
93
|
+
/**
|
|
94
|
+
* Read the live `effort.enabled` switch.
|
|
95
|
+
*
|
|
96
|
+
* A getter, not a value: a config-only settings save flips this without
|
|
97
|
+
* remounting the plugin, and the next delegated selection must see the value
|
|
98
|
+
* actually in force.
|
|
99
|
+
*/
|
|
100
|
+
enabled: () => boolean;
|
|
101
|
+
/** Resolve one session id to a live session (the parent lookup). */
|
|
102
|
+
sessionById?: (id: string) => SessionLike | undefined;
|
|
103
|
+
/** Diagnostic sink for non-fatal degradation (never throws). */
|
|
104
|
+
warn?: (message: string) => void;
|
|
105
|
+
}
|
|
106
|
+
/** What {@link installDelegatedEffortInheritance} installed. */
|
|
107
|
+
export interface DelegatedEffortInheritance {
|
|
108
|
+
/** How many delegated selections have been rewritten. */
|
|
109
|
+
readonly rewrites: number;
|
|
110
|
+
/** How many records have been written to child logs. */
|
|
111
|
+
readonly records: number;
|
|
112
|
+
/** Detach the listener; idempotent. */
|
|
113
|
+
dispose(): void;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Whether one session is a delegated agent's.
|
|
117
|
+
*
|
|
118
|
+
* `delegationDepth` is authoritative when present; `origin: 'subagent'` covers a
|
|
119
|
+
* header written before depth was recorded. A main session has neither.
|
|
120
|
+
* @param header - the session header, when the session has one.
|
|
121
|
+
* @returns whether this session is a delegated child.
|
|
122
|
+
*/
|
|
123
|
+
export declare function isDelegatedSession(header: SessionHeaderLike | undefined): boolean;
|
|
124
|
+
/**
|
|
125
|
+
* Fold one session's selection the way the host projection does.
|
|
126
|
+
*
|
|
127
|
+
* `model/selection` sets `pending`; a matching `request/header` retires it into
|
|
128
|
+
* `lastUsed`. `model.current()` reads `pending ?? lastUsed`, so this is the exact
|
|
129
|
+
* value the loop would fix for the next step.
|
|
130
|
+
* @param session - the session to read.
|
|
131
|
+
* @returns the selection in force, or undefined when none was ever recorded.
|
|
132
|
+
*/
|
|
133
|
+
export declare function currentSelectionOf(session: SessionLike | undefined): SelectionData | undefined;
|
|
134
|
+
/**
|
|
135
|
+
* Install the delegated-agent effort inheritance.
|
|
136
|
+
*
|
|
137
|
+
* The listener observes `model/selection` on every session and settles the
|
|
138
|
+
* delegated ones off the current append, never inside it.
|
|
139
|
+
* @param ctx - the plugin context whose `session/event` feed is observed.
|
|
140
|
+
* @param options - live policy and the parent lookup.
|
|
141
|
+
* @returns the installation handle.
|
|
142
|
+
*/
|
|
143
|
+
export declare function installDelegatedEffortInheritance(ctx: Context, options: DelegatedEffortInheritanceOptions): DelegatedEffortInheritance;
|
|
144
|
+
export {};
|
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
import { isEffortTrigger } from './effort.js';
|
|
2
|
+
import { appendEffortInheritRecord } from './session-audit.js';
|
|
3
|
+
/**
|
|
4
|
+
* Delegated agents cannot decide their own reasoning effort — so let them inherit.
|
|
5
|
+
*
|
|
6
|
+
* ## Why this exists (g-048)
|
|
7
|
+
*
|
|
8
|
+
* `executor.reasoning_effort: "reflex"` marks a deployment as adaptive: the
|
|
9
|
+
* plugin decides the level per turn. For a delegated agent that decision used to
|
|
10
|
+
* be taken inside the `agent/request` waterfall, and `dsh-agent-loop` refuses
|
|
11
|
+
* exactly that — it fixes the step's effort during step preparation and rejects
|
|
12
|
+
* any later proposal:
|
|
13
|
+
*
|
|
14
|
+
* agent/request proposed reasoning effort "low" after step preparation fixed
|
|
15
|
+
* "reflex"; use agent.model.select() before step preparation
|
|
16
|
+
*
|
|
17
|
+
* The waterfall may re-route a request; it may not re-decide the effort. And
|
|
18
|
+
* `agent/pre-step` cannot help either: the loop reads `model.current()` for that
|
|
19
|
+
* step *before* the waterfall runs, so a `modelSelection` handed back from
|
|
20
|
+
* `pre-step` is already too late. There is no host hook between "the selection is
|
|
21
|
+
* recorded" and "the step reads it".
|
|
22
|
+
*
|
|
23
|
+
* ## What this does instead (C1)
|
|
24
|
+
*
|
|
25
|
+
* The marker the delegated agent would have decided on is replaced on its own
|
|
26
|
+
* `model/selection` — the very log entry the loop folds to obtain `model.current()`
|
|
27
|
+
* — with the level its parent session is currently using. The step then fixes a
|
|
28
|
+
* concrete level, the request waterfall has nothing left to change, and the loop's
|
|
29
|
+
* contract holds by construction rather than by suppressing a check.
|
|
30
|
+
*
|
|
31
|
+
* ## Why the rewrite is a second `model/selection` event
|
|
32
|
+
*
|
|
33
|
+
* The arriving event is deep-frozen (the Session snapshots and freezes every
|
|
34
|
+
* payload) and the append that published it is still on the stack, so a listener
|
|
35
|
+
* cannot rewrite it in place: `session append cannot reenter while another append
|
|
36
|
+
* is being published`. Returning *before* the projection folds is not an option
|
|
37
|
+
* either — listeners run in registration order, and the projection that serves
|
|
38
|
+
* `model.current()` is registered by the agent runtime, ahead of this plugin.
|
|
39
|
+
*
|
|
40
|
+
* So the rewrite is committed immediately *after* the current append completes,
|
|
41
|
+
* as one further `model/selection`. Only the last one counts: the selection fold
|
|
42
|
+
* takes `pending` from the newest `model/selection`, which is exactly the value
|
|
43
|
+
* `model.current()` returns. Nothing reads the selection in between — the driver
|
|
44
|
+
* reaches its next step only after the current one has fully committed.
|
|
45
|
+
*
|
|
46
|
+
* Deferring also buys the ordering the parent needs. A child's selection may be
|
|
47
|
+
* recorded before the parent has one, and the parent's own level may change
|
|
48
|
+
* later; settling on a microtask keeps the copy current without depending on
|
|
49
|
+
* which session was configured first.
|
|
50
|
+
*
|
|
51
|
+
* ## Boundaries
|
|
52
|
+
*
|
|
53
|
+
* - **Only delegated sessions.** A `delegationDepth > 0` header or a `subagent`
|
|
54
|
+
* origin marks one; a main session is never touched, so the adaptive behaviour
|
|
55
|
+
* its deployment asked for is bit-for-bit unchanged.
|
|
56
|
+
* - **Only the marker.** `reflex`/`auto` is rewritten. A concrete level — the
|
|
57
|
+
* caller's own choice — is left exactly as recorded.
|
|
58
|
+
* - **`effort.enabled: false` keeps today's behaviour**, i.e. nothing happens
|
|
59
|
+
* here and the interceptor clears the marker later, landing on the adapter's
|
|
60
|
+
* default. Inheriting the parent's level would silently change what a switched
|
|
61
|
+
* off deployment does.
|
|
62
|
+
* - **No parent level, no inheritance:** the marker is removed, which is the
|
|
63
|
+
* adapter's own default — the same outcome the disabled switch has, reached for
|
|
64
|
+
* a different reason (recorded as such).
|
|
65
|
+
*
|
|
66
|
+
* @module dsh-reflex/effort-delegation
|
|
67
|
+
*/
|
|
68
|
+
/** The only reason this module rewrites anything. */
|
|
69
|
+
export const DELEGATION_EFFORT_REASON = 'subagent-cannot-decide';
|
|
70
|
+
/**
|
|
71
|
+
* Whether one session is a delegated agent's.
|
|
72
|
+
*
|
|
73
|
+
* `delegationDepth` is authoritative when present; `origin: 'subagent'` covers a
|
|
74
|
+
* header written before depth was recorded. A main session has neither.
|
|
75
|
+
* @param header - the session header, when the session has one.
|
|
76
|
+
* @returns whether this session is a delegated child.
|
|
77
|
+
*/
|
|
78
|
+
export function isDelegatedSession(header) {
|
|
79
|
+
if (!header || typeof header !== 'object')
|
|
80
|
+
return false;
|
|
81
|
+
if (typeof header.delegationDepth === 'number')
|
|
82
|
+
return header.delegationDepth > 0;
|
|
83
|
+
return header.origin === 'subagent';
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Read the concrete level a selection carries.
|
|
87
|
+
* @param selection - the selection to inspect.
|
|
88
|
+
* @returns the level, or undefined when it carries none (or carries the marker).
|
|
89
|
+
*/
|
|
90
|
+
function concreteLevel(selection) {
|
|
91
|
+
const effort = selection?.reasoningEffort;
|
|
92
|
+
if (typeof effort !== 'string')
|
|
93
|
+
return undefined;
|
|
94
|
+
return isEffortTrigger(effort) ? undefined : effort;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Fold one session's selection the way the host projection does.
|
|
98
|
+
*
|
|
99
|
+
* `model/selection` sets `pending`; a matching `request/header` retires it into
|
|
100
|
+
* `lastUsed`. `model.current()` reads `pending ?? lastUsed`, so this is the exact
|
|
101
|
+
* value the loop would fix for the next step.
|
|
102
|
+
* @param session - the session to read.
|
|
103
|
+
* @returns the selection in force, or undefined when none was ever recorded.
|
|
104
|
+
*/
|
|
105
|
+
export function currentSelectionOf(session) {
|
|
106
|
+
const events = session?.snapshotEvents?.() ?? [];
|
|
107
|
+
let pending;
|
|
108
|
+
let lastUsed;
|
|
109
|
+
const same = (a, b) => a === b ||
|
|
110
|
+
(a !== undefined &&
|
|
111
|
+
b !== undefined &&
|
|
112
|
+
a.provider === b.provider &&
|
|
113
|
+
a.model === b.model &&
|
|
114
|
+
a.reasoningEffort === b.reasoningEffort);
|
|
115
|
+
for (const event of events) {
|
|
116
|
+
if (event.type === 'model/selection') {
|
|
117
|
+
const data = event.data;
|
|
118
|
+
if (data && typeof data.provider === 'string' && typeof data.model === 'string')
|
|
119
|
+
pending = data;
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
if (event.type !== 'request/header')
|
|
123
|
+
continue;
|
|
124
|
+
const config = event.data?.header?.config;
|
|
125
|
+
if (!config || typeof config.provider !== 'string' || typeof config.model !== 'string')
|
|
126
|
+
continue;
|
|
127
|
+
lastUsed = config;
|
|
128
|
+
if (same(pending, config))
|
|
129
|
+
pending = undefined;
|
|
130
|
+
}
|
|
131
|
+
return pending ?? lastUsed;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Build the audit record for one rewrite.
|
|
135
|
+
* @param selection - the child selection that carried the marker.
|
|
136
|
+
* @param requested - the marker that was there.
|
|
137
|
+
* @param parentLevel - the level copied from the parent, when there was one.
|
|
138
|
+
* @param parentLevel - how the parent looked up.
|
|
139
|
+
* @param agentId - the delegated agent's id.
|
|
140
|
+
* @param depth - the delegated agent's depth.
|
|
141
|
+
* @returns the record payload.
|
|
142
|
+
*/
|
|
143
|
+
function inheritRecord(selection, requested, parentLevel, parentState, agentId, depth) {
|
|
144
|
+
return {
|
|
145
|
+
requested,
|
|
146
|
+
applied: parentLevel ?? null,
|
|
147
|
+
reason: DELEGATION_EFFORT_REASON,
|
|
148
|
+
...(parentLevel === undefined ? {} : { inherited: parentLevel }),
|
|
149
|
+
parentLevel: parentState,
|
|
150
|
+
provider: selection.provider,
|
|
151
|
+
model: selection.model,
|
|
152
|
+
line: parentLevel === undefined
|
|
153
|
+
? `delegated agent: configured "${requested}", cannot decide per turn — marker removed (adapter default)`
|
|
154
|
+
: `delegated agent: configured "${requested}", cannot decide per turn — inherited parent level "${parentLevel}"`,
|
|
155
|
+
at: Date.now(),
|
|
156
|
+
...(agentId === undefined ? {} : { agentId }),
|
|
157
|
+
...(depth === undefined ? {} : { delegationDepth: depth })
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Install the delegated-agent effort inheritance.
|
|
162
|
+
*
|
|
163
|
+
* The listener observes `model/selection` on every session and settles the
|
|
164
|
+
* delegated ones off the current append, never inside it.
|
|
165
|
+
* @param ctx - the plugin context whose `session/event` feed is observed.
|
|
166
|
+
* @param options - live policy and the parent lookup.
|
|
167
|
+
* @returns the installation handle.
|
|
168
|
+
*/
|
|
169
|
+
export function installDelegatedEffortInheritance(ctx, options) {
|
|
170
|
+
let rewrites = 0;
|
|
171
|
+
let records = 0;
|
|
172
|
+
let disposed = false;
|
|
173
|
+
/**
|
|
174
|
+
* Rewrite one child selection, then record what happened.
|
|
175
|
+
*
|
|
176
|
+
* Every step is best-effort: this runs off a committed event, and an audit or
|
|
177
|
+
* lookup failure must not become a failed turn.
|
|
178
|
+
* @param session - the delegated agent's session.
|
|
179
|
+
* @param selection - the child selection carrying the marker.
|
|
180
|
+
* @param requested - the marker that was there.
|
|
181
|
+
*/
|
|
182
|
+
const settle = (session, selection, requested) => {
|
|
183
|
+
if (disposed)
|
|
184
|
+
return;
|
|
185
|
+
const header = session.header;
|
|
186
|
+
const parentId = header?.parentSession;
|
|
187
|
+
let parentLevel;
|
|
188
|
+
let parentState = 'absent';
|
|
189
|
+
try {
|
|
190
|
+
if (parentId !== undefined && options.sessionById !== undefined) {
|
|
191
|
+
const parent = options.sessionById(String(parentId));
|
|
192
|
+
if (parent === undefined)
|
|
193
|
+
parentState = 'absent';
|
|
194
|
+
else {
|
|
195
|
+
const level = concreteLevel(currentSelectionOf(parent));
|
|
196
|
+
if (level === undefined)
|
|
197
|
+
parentState = 'absent';
|
|
198
|
+
else {
|
|
199
|
+
parentLevel = level;
|
|
200
|
+
parentState = 'present';
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
catch (error) {
|
|
206
|
+
// A hostile or half-built session must not swallow the rewrite itself:
|
|
207
|
+
// without a readable parent the marker is removed, which is still valid.
|
|
208
|
+
parentState = 'unreadable';
|
|
209
|
+
parentLevel = undefined;
|
|
210
|
+
options.warn?.(`dsh-reflex: could not read the parent level of a delegated agent: ${String(error)}`);
|
|
211
|
+
}
|
|
212
|
+
try {
|
|
213
|
+
// A second `model/selection` is the rewrite: the fold takes `pending` from
|
|
214
|
+
// the newest one, which is what the next step's `model.current()` reads.
|
|
215
|
+
session.append('model/selection', {
|
|
216
|
+
provider: selection.provider,
|
|
217
|
+
model: selection.model,
|
|
218
|
+
...(parentLevel === undefined ? {} : { reasoningEffort: parentLevel })
|
|
219
|
+
});
|
|
220
|
+
rewrites += 1;
|
|
221
|
+
}
|
|
222
|
+
catch (error) {
|
|
223
|
+
options.warn?.(`dsh-reflex: could not inherit a parent effort level: ${String(error)}`);
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
const record = inheritRecord(selection, requested, parentLevel, parentState, session.id, header?.delegationDepth);
|
|
227
|
+
if (appendEffortInheritRecord(session, record) !== undefined)
|
|
228
|
+
records += 1;
|
|
229
|
+
};
|
|
230
|
+
const stop = ctx.on('session/event', (session, event) => {
|
|
231
|
+
if (disposed || event?.type !== 'model/selection')
|
|
232
|
+
return;
|
|
233
|
+
const data = event.data;
|
|
234
|
+
if (!data || typeof data.provider !== 'string' || typeof data.model !== 'string')
|
|
235
|
+
return;
|
|
236
|
+
const requested = data.reasoningEffort;
|
|
237
|
+
if (requested === undefined || !isEffortTrigger(requested))
|
|
238
|
+
return;
|
|
239
|
+
if (!isDelegatedSession(session?.header))
|
|
240
|
+
return;
|
|
241
|
+
// The disabled switch keeps its existing behaviour; the interceptor clears
|
|
242
|
+
// the marker on the way out, so touching the selection here would change it.
|
|
243
|
+
let enabled = true;
|
|
244
|
+
try {
|
|
245
|
+
enabled = options.enabled();
|
|
246
|
+
}
|
|
247
|
+
catch {
|
|
248
|
+
enabled = true;
|
|
249
|
+
}
|
|
250
|
+
if (!enabled)
|
|
251
|
+
return;
|
|
252
|
+
// Off the current append: the log cannot be appended to while the event that
|
|
253
|
+
// reported it is still being published.
|
|
254
|
+
queueMicrotask(() => {
|
|
255
|
+
if (disposed)
|
|
256
|
+
return;
|
|
257
|
+
try {
|
|
258
|
+
settle(session, data, requested);
|
|
259
|
+
}
|
|
260
|
+
catch (error) {
|
|
261
|
+
options.warn?.(`dsh-reflex: delegated effort inheritance failed: ${String(error)}`);
|
|
262
|
+
}
|
|
263
|
+
});
|
|
264
|
+
});
|
|
265
|
+
return {
|
|
266
|
+
get rewrites() {
|
|
267
|
+
return rewrites;
|
|
268
|
+
},
|
|
269
|
+
get records() {
|
|
270
|
+
return records;
|
|
271
|
+
},
|
|
272
|
+
dispose() {
|
|
273
|
+
if (disposed)
|
|
274
|
+
return;
|
|
275
|
+
disposed = true;
|
|
276
|
+
stop();
|
|
277
|
+
}
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
//# sourceMappingURL=effort-delegation.js.map
|