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.
Files changed (124) hide show
  1. package/README.md +20 -6
  2. package/client.js +3511 -185
  3. package/dist/attribution.d.ts +266 -0
  4. package/dist/attribution.js +238 -0
  5. package/dist/attribution.js.map +1 -0
  6. package/dist/bridge.d.ts +311 -13
  7. package/dist/bridge.js +714 -42
  8. package/dist/bridge.js.map +1 -1
  9. package/dist/client-bundle.js +4 -1
  10. package/dist/client-bundle.js.map +1 -1
  11. package/dist/command.js +10 -0
  12. package/dist/command.js.map +1 -1
  13. package/dist/config.d.ts +530 -22
  14. package/dist/config.js +808 -27
  15. package/dist/config.js.map +1 -1
  16. package/dist/delegation-dispatch.d.ts +132 -0
  17. package/dist/delegation-dispatch.js +186 -0
  18. package/dist/delegation-dispatch.js.map +1 -0
  19. package/dist/delegation-health.d.ts +131 -0
  20. package/dist/delegation-health.js +97 -0
  21. package/dist/delegation-health.js.map +1 -0
  22. package/dist/delegation.d.ts +148 -0
  23. package/dist/delegation.js +186 -0
  24. package/dist/delegation.js.map +1 -0
  25. package/dist/effort-delegation.d.ts +144 -0
  26. package/dist/effort-delegation.js +280 -0
  27. package/dist/effort-delegation.js.map +1 -0
  28. package/dist/effort.d.ts +141 -0
  29. package/dist/effort.js +251 -9
  30. package/dist/effort.js.map +1 -1
  31. package/dist/host-patch.d.ts +156 -0
  32. package/dist/host-patch.js +534 -0
  33. package/dist/host-patch.js.map +1 -0
  34. package/dist/index.d.ts +12 -3
  35. package/dist/index.js +99 -7
  36. package/dist/index.js.map +1 -1
  37. package/dist/interventions.d.ts +98 -373
  38. package/dist/interventions.js +442 -1702
  39. package/dist/interventions.js.map +1 -1
  40. package/dist/panel-api.d.ts +328 -4
  41. package/dist/panel-api.js +322 -15
  42. package/dist/panel-api.js.map +1 -1
  43. package/dist/panel-mount.d.ts +81 -22
  44. package/dist/panel-mount.js +228 -7
  45. package/dist/panel-mount.js.map +1 -1
  46. package/dist/routing.d.ts +23 -18
  47. package/dist/routing.js +471 -153
  48. package/dist/routing.js.map +1 -1
  49. package/dist/session-audit.d.ts +70 -0
  50. package/dist/session-audit.js +73 -0
  51. package/dist/session-audit.js.map +1 -1
  52. package/dist/systemone-probe.d.ts +114 -0
  53. package/dist/systemone-probe.js +383 -0
  54. package/dist/systemone-probe.js.map +1 -0
  55. package/dist/testing.d.ts +212 -7
  56. package/dist/testing.js +333 -27
  57. package/dist/testing.js.map +1 -1
  58. package/dist/tools.d.ts +109 -3
  59. package/dist/tools.js +103 -4
  60. package/dist/tools.js.map +1 -1
  61. package/dist/unconfigured-backend.d.ts +72 -0
  62. package/dist/unconfigured-backend.js +94 -0
  63. package/dist/unconfigured-backend.js.map +1 -0
  64. package/dist/vendor/harness-reflex/backend/factory.d.ts +31 -1
  65. package/dist/vendor/harness-reflex/backend/factory.js +18 -3
  66. package/dist/vendor/harness-reflex/backend/factory.js.map +1 -1
  67. package/dist/vendor/harness-reflex/backend/jev.d.ts +20 -0
  68. package/dist/vendor/harness-reflex/backend/jev.js +11 -4
  69. package/dist/vendor/harness-reflex/backend/jev.js.map +1 -1
  70. package/dist/vendor/harness-reflex/backend/simple-jev.d.ts +16 -0
  71. package/dist/vendor/harness-reflex/backend/simple-jev.js +17 -6
  72. package/dist/vendor/harness-reflex/backend/simple-jev.js.map +1 -1
  73. package/dist/vendor/harness-reflex/core/closing.d.ts +90 -0
  74. package/dist/vendor/harness-reflex/core/closing.js +111 -0
  75. package/dist/vendor/harness-reflex/core/closing.js.map +1 -0
  76. package/dist/vendor/harness-reflex/core/evidence.d.ts +119 -0
  77. package/dist/vendor/harness-reflex/core/evidence.js +209 -0
  78. package/dist/vendor/harness-reflex/core/evidence.js.map +1 -0
  79. package/dist/vendor/harness-reflex/core/judge.d.ts +221 -0
  80. package/dist/vendor/harness-reflex/core/judge.js +251 -0
  81. package/dist/vendor/harness-reflex/core/judge.js.map +1 -0
  82. package/dist/vendor/harness-reflex/core/orchestrate-closing.d.ts +237 -0
  83. package/dist/vendor/harness-reflex/core/orchestrate-closing.js +250 -0
  84. package/dist/vendor/harness-reflex/core/orchestrate-closing.js.map +1 -0
  85. package/dist/vendor/harness-reflex/core/orchestrate-correction.d.ts +209 -0
  86. package/dist/vendor/harness-reflex/core/orchestrate-correction.js +141 -0
  87. package/dist/vendor/harness-reflex/core/orchestrate-correction.js.map +1 -0
  88. package/dist/vendor/harness-reflex/core/orchestrate-host.d.ts +225 -0
  89. package/dist/vendor/harness-reflex/core/orchestrate-host.js +80 -0
  90. package/dist/vendor/harness-reflex/core/orchestrate-host.js.map +1 -0
  91. package/dist/vendor/harness-reflex/core/orchestrate-stagnation.d.ts +259 -0
  92. package/dist/vendor/harness-reflex/core/orchestrate-stagnation.js +270 -0
  93. package/dist/vendor/harness-reflex/core/orchestrate-stagnation.js.map +1 -0
  94. package/dist/vendor/harness-reflex/core/orchestrate.d.ts +357 -0
  95. package/dist/vendor/harness-reflex/core/orchestrate.js +418 -0
  96. package/dist/vendor/harness-reflex/core/orchestrate.js.map +1 -0
  97. package/dist/vendor/harness-reflex/core/policy.d.ts +122 -0
  98. package/dist/vendor/harness-reflex/core/policy.js +102 -0
  99. package/dist/vendor/harness-reflex/core/policy.js.map +1 -0
  100. package/dist/vendor/harness-reflex/core/prune-plan.d.ts +141 -0
  101. package/dist/vendor/harness-reflex/core/prune-plan.js +390 -0
  102. package/dist/vendor/harness-reflex/core/prune-plan.js.map +1 -0
  103. package/dist/vendor/harness-reflex/core/text.d.ts +36 -0
  104. package/dist/vendor/harness-reflex/core/text.js +66 -0
  105. package/dist/vendor/harness-reflex/core/text.js.map +1 -0
  106. package/dist/vendor/harness-reflex/ports/audit.d.ts +18 -0
  107. package/dist/vendor/harness-reflex/ports/audit.js +11 -0
  108. package/dist/vendor/harness-reflex/ports/audit.js.map +1 -0
  109. package/dist/vendor/harness-reflex/ports/clock.d.ts +14 -0
  110. package/dist/vendor/harness-reflex/ports/clock.js +11 -0
  111. package/dist/vendor/harness-reflex/ports/clock.js.map +1 -0
  112. package/dist/vendor/harness-reflex/ports/decision.d.ts +75 -0
  113. package/dist/vendor/harness-reflex/ports/decision.js +2 -0
  114. package/dist/vendor/harness-reflex/ports/decision.js.map +1 -0
  115. package/dist/vendor/harness-reflex/ports/index.d.ts +14 -0
  116. package/dist/vendor/harness-reflex/ports/index.js +2 -0
  117. package/dist/vendor/harness-reflex/ports/index.js.map +1 -0
  118. package/dist/vendor/harness-reflex/ports/log.d.ts +22 -0
  119. package/dist/vendor/harness-reflex/ports/log.js +12 -0
  120. package/dist/vendor/harness-reflex/ports/log.js.map +1 -0
  121. package/dist/vendor/harness-reflex/ports/state.d.ts +46 -0
  122. package/dist/vendor/harness-reflex/ports/state.js +13 -0
  123. package/dist/vendor/harness-reflex/ports/state.js.map +1 -0
  124. package/package.json +25 -13
@@ -35,6 +35,18 @@ export const INTERVENTION_RECORD_TYPE = 'plugin:dsh-reflex/intervention';
35
35
  * permission, and the Session's own retention governs the copy's lifetime.
36
36
  */
37
37
  export const PRUNED_ORIGINAL_RECORD_TYPE = 'plugin:dsh-reflex/pruned-original';
38
+ /**
39
+ * Session-log record type of one delegated-agent effort downgrade.
40
+ *
41
+ * A delegated agent that was configured to decide its own effort (`reflex` /
42
+ * `auto`) cannot do so: the loop fixes the step's effort before any plugin hook
43
+ * runs, so the decision has to be taken on the *selection* instead, before that
44
+ * step reads it. That is a change of intent, not a routine decision, so it gets
45
+ * its own record rather than a disguised `effort` one: the configured marker is
46
+ * kept verbatim next to the level actually inherited, and a reader can see that
47
+ * the level came from the parent rather than from a System 1 judgment.
48
+ */
49
+ export const EFFORT_INHERIT_RECORD_TYPE = 'plugin:dsh-reflex/effort-inherit';
38
50
  /**
39
51
  * Project one status onto the audit payload.
40
52
  * @param status - the published effort status.
@@ -133,6 +145,67 @@ export function isEffortAuditRecord(data) {
133
145
  typeof record.at === 'number' &&
134
146
  (record.applied === null || typeof record.applied === 'string'));
135
147
  }
148
+ /**
149
+ * Append one delegated-agent effort downgrade to a Session's log.
150
+ *
151
+ * Best-effort by the same contract as every other audit record here: a missing
152
+ * session (synthetic agent) or a rejected payload is swallowed and reported as
153
+ * `undefined`, never allowed to fail a turn.
154
+ * @param session - the delegated agent's session, when it has one.
155
+ * @param record - the rewrite to record.
156
+ * @returns the committed sequence number, or `undefined` when nothing was written.
157
+ */
158
+ export function appendEffortInheritRecord(session, record) {
159
+ const target = session;
160
+ if (!target || typeof appendPluginRecord !== 'function')
161
+ return undefined;
162
+ try {
163
+ return appendPluginRecord(target, EFFORT_INHERIT_RECORD_TYPE, record);
164
+ }
165
+ catch {
166
+ return undefined;
167
+ }
168
+ }
169
+ /**
170
+ * Read back the delegated-agent effort downgrades of one Session log.
171
+ * @param events - the session log, or any slice of it.
172
+ * @returns the validated records, oldest first; malformed payloads are dropped.
173
+ */
174
+ export function effortInheritRecordsOf(events) {
175
+ const records = [];
176
+ for (const event of events ?? []) {
177
+ let record;
178
+ try {
179
+ record = pluginRecordOf(event);
180
+ }
181
+ catch {
182
+ continue;
183
+ }
184
+ if (!record || record.type !== EFFORT_INHERIT_RECORD_TYPE)
185
+ continue;
186
+ if (isEffortInheritAuditRecord(record.data))
187
+ records.push(record.data);
188
+ }
189
+ return records;
190
+ }
191
+ /**
192
+ * Validate one restored downgrade payload before a reader trusts it.
193
+ * @param data - the payload committed by an earlier build.
194
+ * @returns whether it carries the fields this plugin writes.
195
+ */
196
+ export function isEffortInheritAuditRecord(data) {
197
+ if (typeof data !== 'object' || data === null)
198
+ return false;
199
+ const record = data;
200
+ return (typeof record.requested === 'string' &&
201
+ (record.applied === null || typeof record.applied === 'string') &&
202
+ record.reason === 'subagent-cannot-decide' &&
203
+ (record.parentLevel === 'present' || record.parentLevel === 'absent' || record.parentLevel === 'unreadable') &&
204
+ typeof record.provider === 'string' &&
205
+ typeof record.model === 'string' &&
206
+ typeof record.line === 'string' &&
207
+ typeof record.at === 'number');
208
+ }
136
209
  /**
137
210
  * Append one intervention decision to a Session's log.
138
211
  *
@@ -1 +1 @@
1
- {"version":3,"file":"session-audit.js","sourceRoot":"","sources":["../src/session-audit.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAE,kBAAkB,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAK9E,oDAAoD;AACpD,MAAM,CAAC,MAAM,kBAAkB,GAAG,0BAA0B,CAAC;AAE7D;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAG,gCAAgC,CAAC;AAEzE;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,2BAA2B,GAAG,mCAAmC,CAAC;AA0M/E;;;;GAIG;AACH,MAAM,UAAU,mBAAmB,CAAC,MAA0B;IAC5D,OAAO;QACL,KAAK,EAAE,MAAM,CAAC,KAAK;QACnB,OAAO,EAAE,MAAM,CAAC,OAAO,IAAI,IAAI;QAC/B,OAAO,EAAE,MAAM,CAAC,OAAO;QACvB,OAAO,EAAE,MAAM,CAAC,OAAO;QACvB,MAAM,EAAE,MAAM,CAAC,MAAM;QACrB,UAAU,EAAE,MAAM,CAAC,UAAU;QAC7B,SAAS,EAAE,MAAM,CAAC,SAAS;QAC3B,QAAQ,EAAE,MAAM,CAAC,QAAQ;QACzB,KAAK,EAAE,MAAM,CAAC,KAAK;QACnB,IAAI,EAAE,MAAM,CAAC,IAAI;QACjB,EAAE,EAAE,MAAM,CAAC,EAAE;QACb,GAAG,CAAC,MAAM,CAAC,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,EAAE,CAAC;QACpE,GAAG,CAAC,MAAM,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,EAAE,CAAC;QAC3D,GAAG,CAAC,MAAM,CAAC,eAAe,KAAK,S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S;QACrE,IAAI,sBAAsB,CAAC,MAAM,CAAC,IAAI,CAAC;YAAE,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IACrE,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,UAAU,kBAAkB,CAChC,MAA2C,EAC3C,OAAe;IAEf,IAAI,KAAuC,CAAC;IAC5C,KAAK,MAAM,MAAM,IAAI,iBAAiB,CAAC,MAAM,CAAC,EAAE,CAAC;QAC/C,IAAI,MAAM,CAAC,OAAO,KAAK,OAAO;YAAE,KAAK,GAAG,MAAM,CAAC;IACjD,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,sBAAsB,CAAC,IAAa;IAClD,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,IAAI;QAAE,OAAO,KAAK,CAAC;IAC5D,MAAM,MAAM,GAAG,IAAqC,CAAC;IACrD,OAAO,CACL,OAAO,MAAM,CAAC,OAAO,KAAK,QAAQ;QAClC,OAAO,MAAM,CAAC,MAAM,KAAK,QAAQ;QACjC,OAAO,MAAM,CAAC,MAAM,KAAK,QAAQ;QACjC,OAAO,MAAM,CAAC,IAAI,KAAK,QAAQ;QAC/B,OAAO,MAAM,CAAC,IAAI,KAAK,QAAQ;QAC/B,OAAO,MAAM,CAAC,IAAI,KAAK,QAAQ;QAC/B,OAAO,MAAM,CAAC,KAAK,KAAK,QAAQ;QAChC,OAAO,MAAM,CAAC,IAAI,KAAK,QAAQ;QAC/B,MAAM,CAAC,IAAI,CAAC,MAAM,KAAK,MAAM,CAAC,KAAK;QACnC,OAAO,MAAM,CAAC,EAAE,KAAK,QAAQ,CAC9B,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Session-log audit of the adaptive effort decisions.\n *\n * Criterion: the effort actually dispatched has to be recorded where a human can\n * audit it, **without** polluting what the model reads next. The Session log has\n * exactly one surface with that property: experimental plugin records are\n * committed events marked `ignorable`, they are retained by fork and resume, and\n * they never enter the model-visible surface (unlike a `user`/`system` message,\n * which would re-enter the prompt and could even be re-interpreted as\n * instructions by the model).\n *\n * So the audit trail lives here and nowhere else: one record per adaptive\n * decision, read back with {@link effortRecordsOf}. The record's owner validates\n * `data` on read, because a restored log carries whatever an earlier build wrote.\n */\nimport { appendPluginRecord, pluginRecordOf } from '@deepseek-ai/dsh-session';\nimport type { Session, SessionEvent } from '@deepseek-ai/dsh-session';\n\nimport type { ReflexEffortStatus } from './effort.js';\n\n/** Session-log record type owned by this plugin. */\nexport const EFFORT_RECORD_TYPE = 'plugin:dsh-reflex/effort';\n\n/**\n * Session-log record type of one automatic-intervention decision.\n *\n * The same channel as the effort audit, for the same reason: an intervention\n * that was *planned* must be auditable even when it was not applied (observe\n * mode), and neither case may add anything the model can read.\n */\nexport const INTERVENTION_RECORD_TYPE = 'plugin:dsh-reflex/intervention';\n\n/**\n * Session-log record type of one retained pre-prune payload.\n *\n * A reduction is only installed after its original has been written here, so\n * \"the full output is retrievable\" is a fact about the log rather than a claim\n * about it: the installed text names the locator, and a reader resolves the\n * locator back to the exact bytes that were replaced. The same append-only,\n * ignorable, model-invisible channel as the audit trail — no new file, no new\n * permission, and the Session's own retention governs the copy's lifetime.\n */\nexport const PRUNED_ORIGINAL_RECORD_TYPE = 'plugin:dsh-reflex/pruned-original';\n\ndeclare module '@deepseek-ai/dsh-session/types' {\n interface PluginRecordMap {\n /** One adaptive reasoning-effort decision, as dispatched. */\n 'plugin:dsh-reflex/effort': EffortAuditRecord;\n /** One planned or applied automatic intervention. */\n 'plugin:dsh-reflex/intervention': InterventionAuditRecord;\n /** One pre-prune payload kept so a replacement stays verifiable. */\n 'plugin:dsh-reflex/pruned-original': PrunedOriginalRecord;\n }\n}\n\n/**\n * One retained pre-prune payload.\n *\n * `text` is the payload *verbatim* — the exact text the reduction replaced — so\n * a reader compares bytes rather than reconstructing them. `digest` is the same\n * identity the judgment, the memo, and the replacement's locator use, which is\n * what makes the record findable without carrying a log offset: offsets shift\n * under fork and resume, a payload digest does not.\n */\nexport interface PrunedOriginalRecord {\n /** Locator the model-visible replacement publishes. */\n locator: string;\n /** Payload identity: `digestOf(text)`, the same key the prune decision used. */\n digest: string;\n /** Identity of the tool call whose result was replaced. */\n callId: string;\n /** Name of that tool. */\n tool: string;\n /** Turn and step the replacement happened in. */\n turn: number;\n step: number;\n /** Characters of `text`. */\n chars: number;\n /** The replaced payload, verbatim. */\n text: string;\n /** Unix epoch milliseconds of the retention. */\n at: number;\n}\n\n/**\n * The JSON payload of one intervention record.\n *\n * Only losslessly serializable scalars: the record is read back by hosts and\n * humans, never replayed into a prompt. `feedback` is the model-facing text the\n * active path delivers — bounded on write, because it is the one field a caller\n * controls and an audit sink must not become a content dump. The four token\n * counters are the accounting contract: `potentialSavedTokens` is what the\n * candidate would have saved, `actualSavedTokens` what the harness really\n * stopped carrying, and the two are equal only in active mode.\n */\nexport interface InterventionAuditRecord {\n /** Capability that planned this action. */\n capability: string;\n /** The planned action name. */\n action: string;\n /** Effective three-state mode at plan time. */\n mode: string;\n /** Whether active mode actually executed the plan. */\n applied: boolean;\n /** Why it was planned, or why it was declined. */\n reason: string;\n /** Model-facing text the active path delivers; empty when none. */\n feedback: string;\n /** Judgment cost paid on this process' CPU (deterministic triggers, floors). */\n localLatencyMs: number;\n /** Judgment cost paid waiting for System 1. */\n remoteLatencyMs: number;\n /** Tokens the judgment itself cost (payload sent to the decision backend). */\n judgeTokens: number;\n /** Tokens of the payload this decision was about. */\n originalTokens: number;\n /** Tokens of the candidate the decision would install. */\n candidateTokens: number;\n /** Tokens the candidate would save; never counted as actual unless applied. */\n potentialSavedTokens: number;\n /** Tokens the harness actually stopped carrying because of this decision. */\n actualSavedTokens: number;\n /** Tokens this decision added to the model-visible surface. */\n injectedTokens: number;\n at: number;\n pattern?: string;\n confidence?: number;\n repeats?: number;\n digest?: string;\n floorApplied?: boolean;\n /** Whether the installed text carried the floor form; same value as `floorApplied`. */\n floored?: boolean;\n /**\n * Whether the installed reduction fell short of the floor's promised share.\n *\n * Present when a prune decision composed a reduction: `true` means the floor\n * form could not be built without growing past the original, so the judged\n * candidate itself was installed. This is the field that separates \"the\n * reduction was real but did not carry `pruneFloorRatio`\" from a real\n * `no-reduction` skip, where nothing was installed at all.\n */\n floorMissed?: boolean;\n /**\n * Whether a floor-missed install had to drop its locator marker.\n *\n * The marker is what tells a reader that a prune happened and where the full\n * payload lives. A candidate that fits only without it is still installed, and\n * this field records the omission instead of leaving it silent. Only ever\n * present with `floorMissed: true`.\n */\n markerOmitted?: boolean;\n memoHit?: boolean;\n agentId?: string;\n turn?: number;\n step?: number;\n /**\n * Why a plan was abandoned instead of planned, when it was.\n *\n * Present exactly on an `action: 'skip'` record: every branch that refuses to\n * plan writes one, so \"why no intervention\" is answerable from the session\n * log instead of a process-local counter. Equal to the record's `reason`,\n * kept as its own field so a reader can select skips without matching prose.\n */\n skip?: string;\n /** Which judging path produced the prune candidate. */\n judgePath?: 'segmented' | 'local' | 'fallback';\n /** Segments handed to System One by the prune judgment (0 when the local path ran). */\n judgedSegments?: number;\n /** Segments beyond the per-request limit, kept deterministically instead. */\n unjudgedSegments?: number;\n /** Segments the candidate the engine composed from kept whole. */\n keptSegments?: number;\n /** Characters of the aggressive-budget candidate the judgment built. */\n aggressiveChars?: number;\n /** Characters of the balanced-budget candidate the judgment built. */\n balancedChars?: number;\n /** Characters of the conservative-budget candidate the judgment built. */\n conservativeChars?: number;\n /** Segments System One really scored (`scores.size`); unreadable answers are absent. */\n scoredSegments?: number;\n /** Segments kept whole without a score: the unjudged safety margin. */\n autoKeptSegments?: number;\n /** Answers returned for a judged segment that carried no usable keep score. */\n unparsedScoreAnswers?: number;\n /** Characters of the payload this decision was about. */\n originalChars?: number;\n /** Characters of the candidate the decision would have installed. */\n candidateChars?: number;\n /** Why the segmented judge fell back to the local candidates, when it did. */\n fallbackReason?: string;\n /**\n * Locator of the controlled copy of the payload this decision replaced.\n *\n * Present exactly when a prune installed a replacement *and* the pre-prune\n * original was durably retained first; absent for every other decision and for\n * a prune that failed open. The locator resolves through\n * {@link readPrunedOriginal}, so the model-visible replacement can always be\n * checked against the bytes it stands in for.\n */\n originalLocator?: string;\n}\n\n/**\n * The JSON payload of one effort record. Deliberately narrower than\n * {@link ReflexEffortStatus}: only losslessly serializable fields, and `applied`\n * is `null` rather than absent when nothing was sent, so a reader never has to\n * tell \"cleared\" from \"field dropped by the serializer\".\n */\nexport interface EffortAuditRecord {\n /** Decided level. */\n level: string;\n /** Effort the rewritten request carried; `null` when the key was cleared. */\n applied: string | null;\n outcome: string;\n trigger: string;\n source: string;\n confidence: number;\n latencyMs: number;\n provider: string;\n model: string;\n /** Status-bar rendering of this decision. */\n line: string;\n /** Unix epoch milliseconds of the decision. */\n at: number;\n agentId?: string;\n role?: string;\n delegationDepth?: number;\n turn?: number;\n step?: number;\n basis?: string[];\n degradedReason?: string;\n task?: string;\n /** Provider the request named before routing. */\n requestedProvider?: string;\n /** Model the request named before routing. */\n requestedModel?: string;\n /** Whether routing moved the request onto another provider/model. */\n switched?: boolean;\n /** Whether the model was held to defend upstream prompt-cache affinity. */\n heldForCache?: boolean;\n /** Effort ids the routed model declared; `[]` when it declares none. */\n supportedEfforts?: string[];\n}\n\n/**\n * Project one status onto the audit payload.\n * @param status - the published effort status.\n * @returns the record payload.\n */\nexport function toEffortAuditRecord(status: ReflexEffortStatus): EffortAuditRecord {\n return {\n level: status.level,\n applied: status.applied ?? null,\n outcome: status.outcome,\n trigger: status.trigger,\n source: status.source,\n confidence: status.confidence,\n latencyMs: status.latencyMs,\n provider: status.provider,\n model: status.model,\n line: status.line,\n at: status.at,\n ...(status.agentId === undefined ? {} : { agentId: status.agentId }),\n ...(status.role === undefined ? {} : { role: status.role }),\n ...(status.delegationDepth === undefined ? {} : { delegationDepth: status.delegationDepth }),\n ...(status.turn === undefined ? {} : { turn: status.turn }),\n ...(status.step === undefined ? {} : { step: status.step }),\n ...(status.basis === undefined ? {} : { basis: status.basis }),\n ...(status.degradedReason === undefined ? {} : { degradedReason: status.degradedReason }),\n ...(status.task === undefined ? {} : { task: status.task }),\n ...(status.requestedProvider === undefined ? {} : { requestedProvider: status.requestedProvider }),\n ...(status.requestedModel === undefined ? {} : { requestedModel: status.requestedModel }),\n ...(status.switched === undefined ? {} : { switched: status.switched }),\n ...(status.heldForCache === undefined ? {} : { heldForCache: status.heldForCache }),\n ...(status.supportedEfforts === undefined ? {} : { supportedEfforts: status.supportedEfforts })\n };\n}\n\n/**\n * Append one effort decision to a Session's log.\n *\n * Best-effort by contract: an audit record is never allowed to fail a turn, so a\n * missing session (synthetic agent), a re-entrant append, or a rejected payload\n * is swallowed and reported as `undefined`.\n *\n * @param session - the requesting agent's session, when it has one.\n * @param status - the decision to record.\n * @returns the committed sequence number, or `undefined` when nothing was written.\n */\nexport function appendEffortRecord(session: unknown, status: ReflexEffortStatus): number | undefined {\n const target = session as Session | undefined;\n if (!target || typeof appendPluginRecord !== 'function') return undefined;\n try {\n return appendPluginRecord(target, EFFORT_RECORD_TYPE, toEffortAuditRecord(status)) as unknown as number;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Read back the effort decisions of one Session log.\n * @param events - the session log, or any slice of it.\n * @returns the validated records, oldest first; malformed payloads are dropped.\n */\nexport function effortRecordsOf(events: readonly SessionEvent[] | undefined): EffortAuditRecord[] {\n const records: EffortAuditRecord[] = [];\n for (const event of events ?? []) {\n let record;\n try {\n record = pluginRecordOf(event);\n } catch {\n continue;\n }\n if (!record || record.type !== EFFORT_RECORD_TYPE) continue;\n if (isEffortAuditRecord(record.data)) records.push(record.data);\n }\n return records;\n}\n\n/**\n * Validate one restored payload before a reader trusts it.\n * @param data - the payload committed by an earlier build.\n * @returns whether it carries the fields this plugin writes.\n */\nexport function isEffortAuditRecord(data: unknown): data is EffortAuditRecord {\n if (typeof data !== 'object' || data === null) return false;\n const record = data as Partial<EffortAuditRecord>;\n return (\n typeof record.level === 'string' &&\n typeof record.outcome === 'string' &&\n typeof record.trigger === 'string' &&\n typeof record.source === 'string' &&\n typeof record.confidence === 'number' &&\n typeof record.latencyMs === 'number' &&\n typeof record.provider === 'string' &&\n typeof record.model === 'string' &&\n typeof record.line === 'string' &&\n typeof record.at === 'number' &&\n (record.applied === null || typeof record.applied === 'string')\n );\n}\n\n/**\n * Append one intervention decision to a Session's log.\n *\n * Best-effort, exactly like the effort audit: a missing session (synthetic\n * agent) or a rejected payload must never fail a turn, so failures are\n * swallowed and reported as `undefined`.\n *\n * @param session - the deciding agent's session, when it has one.\n * @param record - the decision to record.\n * @returns the committed sequence number, or `undefined` when nothing was written.\n */\nexport function appendInterventionRecord(session: unknown, record: InterventionAuditRecord): number | undefined {\n const target = session as Session | undefined;\n if (!target || typeof appendPluginRecord !== 'function') return undefined;\n try {\n return appendPluginRecord(target, INTERVENTION_RECORD_TYPE, boundRecord(record)) as unknown as number;\n } catch {\n return undefined;\n }\n}\n\n/** Longest `feedback` text one audit record may carry, in characters. */\nexport const INTERVENTION_FEEDBACK_MAX_CHARS = 600;\n\n/**\n * Bound the one caller-controlled field before it reaches the durable log.\n * @param record - the freshly built record.\n * @returns a copy whose `feedback` fits the audit budget.\n */\nfunction boundRecord(record: InterventionAuditRecord): InterventionAuditRecord {\n if (record.feedback.length <= INTERVENTION_FEEDBACK_MAX_CHARS) return record;\n return { ...record, feedback: `${record.feedback.slice(0, INTERVENTION_FEEDBACK_MAX_CHARS)}…` };\n}\n\n/**\n * Read back the intervention decisions of one Session log.\n * @param events - the session log, or any slice of it.\n * @returns the validated records, oldest first; malformed payloads are dropped.\n */\nexport function interventionRecordsOf(events: readonly SessionEvent[] | undefined): InterventionAuditRecord[] {\n const records: InterventionAuditRecord[] = [];\n for (const event of events ?? []) {\n let record;\n try {\n record = pluginRecordOf(event);\n } catch {\n continue;\n }\n if (!record || record.type !== INTERVENTION_RECORD_TYPE) continue;\n if (isInterventionAuditRecord(record.data)) records.push(record.data);\n }\n return records;\n}\n\n/**\n * Validate one restored intervention payload before a reader trusts it.\n * @param data - the payload committed by an earlier build.\n * @returns whether it carries the fields this plugin writes.\n */\nexport function isInterventionAuditRecord(data: unknown): data is InterventionAuditRecord {\n if (typeof data !== 'object' || data === null) return false;\n const record = data as Partial<InterventionAuditRecord>;\n return (\n typeof record.capability === 'string' &&\n typeof record.action === 'string' &&\n typeof record.mode === 'string' &&\n typeof record.applied === 'boolean' &&\n typeof record.reason === 'string' &&\n typeof record.feedback === 'string' &&\n typeof record.originalTokens === 'number' &&\n typeof record.candidateTokens === 'number' &&\n typeof record.potentialSavedTokens === 'number' &&\n typeof record.actualSavedTokens === 'number' &&\n typeof record.injectedTokens === 'number' &&\n typeof record.at === 'number'\n );\n}\n\n// ── controlled retention of a pre-prune payload ─────────────────────────────\n\n/**\n * The locator of one payload's retained copy.\n *\n * Derived from the payload's own digest, never from a log offset: a session that\n * is forked, resumed, or re-opened under a new store keeps the same locator for\n * the same payload, while an offset would silently point at another event. The\n * length is fixed, so a replacement can publish the locator without changing\n * size between the observation and the application of the same plan.\n * @param digest - the payload's {@link digestOf} identity.\n * @returns the locator string the replacement carries.\n */\nexport function pruneLocator(digest: string): string {\n return `${PRUNED_ORIGINAL_RECORD_TYPE}#${digest}`;\n}\n\n/** What the engine asks the log to retain before it replaces a payload. */\nexport interface PrunedOriginalRequest {\n /** Payload identity, as the prune decision computed it. */\n digest: string;\n /** Identity and name of the call whose result is about to shrink. */\n callId: string;\n tool: string;\n /** Turn and step of the replacement. */\n turn: number;\n step: number;\n /** The payload verbatim, as the reduction is about to replace it. */\n text: string;\n /** Clock seam; defaults to `Date.now()`. */\n at?: number;\n}\n\n/**\n * Retain one pre-prune payload in a Session's log, and prove that it landed.\n *\n * The read-back is the point of this function. An append that throws, a Session\n * that is not there, and a log that acknowledged a record it did not commit all\n * end the same way for the caller: `undefined`, meaning *the original is not\n * retrievable*, which the engine treats as a reason not to replace anything. A\n * reduction that cannot be checked against its original is worse than no\n * reduction, so this is deliberately fail-closed for the caller while remaining\n * best-effort towards the log.\n *\n * @param session - the deciding agent's session, when it has one.\n * @param request - the payload and its identity.\n * @returns the locator and the committed sequence, or `undefined` when nothing verifiable was written.\n */\nexport function appendPrunedOriginal(\n session: unknown,\n request: PrunedOriginalRequest\n): { locator: string; seq?: number } | undefined {\n const target = session as Session | undefined;\n if (!target || typeof appendPluginRecord !== 'function') return undefined;\n const locator = pruneLocator(request.digest);\n try {\n const record: PrunedOriginalRecord = {\n locator,\n digest: request.digest,\n callId: request.callId,\n tool: request.tool,\n turn: request.turn,\n step: request.step,\n chars: request.text.length,\n text: request.text,\n at: request.at ?? Date.now()\n };\n const seq = appendPluginRecord(target, PRUNED_ORIGINAL_RECORD_TYPE, record) as unknown as number;\n if (!verifiedRetention(target, seq, record)) return undefined;\n return { locator, seq };\n } catch {\n // An unretainable payload is never replaced; the caller fails open.\n return undefined;\n }\n}\n\n/**\n * Whether the committed log really carries the record we just appended.\n * @param session - the session that acknowledged the append.\n * @param seq - the acknowledged sequence number.\n * @param record - the record to find there.\n * @returns whether the log returns it verbatim.\n */\nfunction verifiedRetention(session: Session, seq: number, record: PrunedOriginalRecord): boolean {\n const reader = session as unknown as { eventAt?: (seq: unknown) => SessionEvent | undefined };\n const eventAt = reader.eventAt;\n if (typeof eventAt !== 'function' || !Number.isFinite(seq)) return false;\n const event = eventAt.call(session, seq);\n if (!event) return false;\n const committed = pluginRecordOf(event);\n if (!committed || committed.type !== PRUNED_ORIGINAL_RECORD_TYPE) return false;\n const data = committed.data as Partial<PrunedOriginalRecord> | undefined;\n return data?.digest === record.digest && data.text === record.text && data.chars === record.chars;\n}\n\n/**\n * Read back the retained payloads of one Session log.\n * @param events - the session log, or any slice of it.\n * @returns the validated records, oldest first; malformed payloads are dropped.\n */\nexport function prunedOriginalsOf(events: readonly SessionEvent[] | undefined): PrunedOriginalRecord[] {\n const records: PrunedOriginalRecord[] = [];\n for (const event of events ?? []) {\n let record;\n try {\n record = pluginRecordOf(event);\n } catch {\n continue;\n }\n if (!record || record.type !== PRUNED_ORIGINAL_RECORD_TYPE) continue;\n if (isPrunedOriginalRecord(record.data)) records.push(record.data);\n }\n return records;\n}\n\n/**\n * Resolve one locator against a Session log.\n *\n * A locator names a payload, not a position, so the same payload pruned twice in\n * one session has two records under one locator: the most recent one is returned,\n * which is the copy the live replacement was built beside.\n * @param events - the session log, or any slice of it.\n * @param locator - the locator the replacement published.\n * @returns the retained payload, or `undefined` when this log does not carry it.\n */\nexport function readPrunedOriginal(\n events: readonly SessionEvent[] | undefined,\n locator: string\n): PrunedOriginalRecord | undefined {\n let found: PrunedOriginalRecord | undefined;\n for (const record of prunedOriginalsOf(events)) {\n if (record.locator === locator) found = record;\n }\n return found;\n}\n\n/**\n * Validate one restored retention payload before a reader trusts it.\n * @param data - the payload committed by an earlier build.\n * @returns whether it carries the fields this plugin writes.\n */\nexport function isPrunedOriginalRecord(data: unknown): data is PrunedOriginalRecord {\n if (typeof data !== 'object' || data === null) return false;\n const record = data as Partial<PrunedOriginalRecord>;\n return (\n typeof record.locator === 'string' &&\n typeof record.digest === 'string' &&\n typeof record.callId === 'string' &&\n typeof record.tool === 'string' &&\n typeof record.turn === 'number' &&\n typeof record.step === 'number' &&\n typeof record.chars === 'number' &&\n typeof record.text === 'string' &&\n record.text.length === record.chars &&\n typeof record.at === 'number'\n );\n}\n"]}
1
+ {"version":3,"file":"session-audit.js","sourceRoot":"","sources":["../src/session-audit.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAE,kBAAkB,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAK9E,oDAAoD;AACpD,MAAM,CAAC,MAAM,kBAAkB,GAAG,0BAA0B,CAAC;AAE7D;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAG,gCAAgC,CAAC;AAEzE;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,2BAA2B,GAAG,mCAAmC,CAAC;AAE/E;;;;;;;;;;GA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AAC,IAAI,CAAC;YAAE,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IACrE,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,UAAU,kBAAkB,CAChC,MAA2C,EAC3C,OAAe;IAEf,IAAI,KAAuC,CAAC;IAC5C,KAAK,MAAM,MAAM,IAAI,iBAAiB,CAAC,MAAM,CAAC,EAAE,CAAC;QAC/C,IAAI,MAAM,CAAC,OAAO,KAAK,OAAO;YAAE,KAAK,GAAG,MAAM,CAAC;IACjD,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,sBAAsB,CAAC,IAAa;IAClD,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,IAAI;QAAE,OAAO,KAAK,CAAC;IAC5D,MAAM,MAAM,GAAG,IAAqC,CAAC;IACrD,OAAO,CACL,OAAO,MAAM,CAAC,OAAO,KAAK,QAAQ;QAClC,OAAO,MAAM,CAAC,MAAM,KAAK,QAAQ;QACjC,OAAO,MAAM,CAAC,MAAM,KAAK,QAAQ;QACjC,OAAO,MAAM,CAAC,IAAI,KAAK,QAAQ;QAC/B,OAAO,MAAM,CAAC,IAAI,KAAK,QAAQ;QAC/B,OAAO,MAAM,CAAC,IAAI,KAAK,QAAQ;QAC/B,OAAO,MAAM,CAAC,KAAK,KAAK,QAAQ;QAChC,OAAO,MAAM,CAAC,IAAI,KAAK,QAAQ;QAC/B,MAAM,CAAC,IAAI,CAAC,MAAM,KAAK,MAAM,CAAC,KAAK;QACnC,OAAO,MAAM,CAAC,EAAE,KAAK,QAAQ,CAC9B,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Session-log audit of the adaptive effort decisions.\n *\n * Criterion: the effort actually dispatched has to be recorded where a human can\n * audit it, **without** polluting what the model reads next. The Session log has\n * exactly one surface with that property: experimental plugin records are\n * committed events marked `ignorable`, they are retained by fork and resume, and\n * they never enter the model-visible surface (unlike a `user`/`system` message,\n * which would re-enter the prompt and could even be re-interpreted as\n * instructions by the model).\n *\n * So the audit trail lives here and nowhere else: one record per adaptive\n * decision, read back with {@link effortRecordsOf}. The record's owner validates\n * `data` on read, because a restored log carries whatever an earlier build wrote.\n */\nimport { appendPluginRecord, pluginRecordOf } from '@deepseek-ai/dsh-session';\nimport type { Session, SessionEvent } from '@deepseek-ai/dsh-session';\n\nimport type { ReflexEffortStatus } from './effort.js';\n\n/** Session-log record type owned by this plugin. */\nexport const EFFORT_RECORD_TYPE = 'plugin:dsh-reflex/effort';\n\n/**\n * Session-log record type of one automatic-intervention decision.\n *\n * The same channel as the effort audit, for the same reason: an intervention\n * that was *planned* must be auditable even when it was not applied (observe\n * mode), and neither case may add anything the model can read.\n */\nexport const INTERVENTION_RECORD_TYPE = 'plugin:dsh-reflex/intervention';\n\n/**\n * Session-log record type of one retained pre-prune payload.\n *\n * A reduction is only installed after its original has been written here, so\n * \"the full output is retrievable\" is a fact about the log rather than a claim\n * about it: the installed text names the locator, and a reader resolves the\n * locator back to the exact bytes that were replaced. The same append-only,\n * ignorable, model-invisible channel as the audit trail — no new file, no new\n * permission, and the Session's own retention governs the copy's lifetime.\n */\nexport const PRUNED_ORIGINAL_RECORD_TYPE = 'plugin:dsh-reflex/pruned-original';\n\n/**\n * Session-log record type of one delegated-agent effort downgrade.\n *\n * A delegated agent that was configured to decide its own effort (`reflex` /\n * `auto`) cannot do so: the loop fixes the step's effort before any plugin hook\n * runs, so the decision has to be taken on the *selection* instead, before that\n * step reads it. That is a change of intent, not a routine decision, so it gets\n * its own record rather than a disguised `effort` one: the configured marker is\n * kept verbatim next to the level actually inherited, and a reader can see that\n * the level came from the parent rather than from a System 1 judgment.\n */\nexport const EFFORT_INHERIT_RECORD_TYPE = 'plugin:dsh-reflex/effort-inherit';\n\ndeclare module '@deepseek-ai/dsh-session/types' {\n interface PluginRecordMap {\n /** One adaptive reasoning-effort decision, as dispatched. */\n 'plugin:dsh-reflex/effort': EffortAuditRecord;\n /** One planned or applied automatic intervention. */\n 'plugin:dsh-reflex/intervention': InterventionAuditRecord;\n /** One pre-prune payload kept so a replacement stays verifiable. */\n 'plugin:dsh-reflex/pruned-original': PrunedOriginalRecord;\n /** One delegated-agent marker replaced by the parent's level. */\n 'plugin:dsh-reflex/effort-inherit': EffortInheritAuditRecord;\n }\n}\n\n/**\n * One retained pre-prune payload.\n *\n * `text` is the payload *verbatim* — the exact text the reduction replaced — so\n * a reader compares bytes rather than reconstructing them. `digest` is the same\n * identity the judgment, the memo, and the replacement's locator use, which is\n * what makes the record findable without carrying a log offset: offsets shift\n * under fork and resume, a payload digest does not.\n */\nexport interface PrunedOriginalRecord {\n /** Locator the model-visible replacement publishes. */\n locator: string;\n /** Payload identity: `digestOf(text)`, the same key the prune decision used. */\n digest: string;\n /** Identity of the tool call whose result was replaced. */\n callId: string;\n /** Name of that tool. */\n tool: string;\n /** Turn and step the replacement happened in. */\n turn: number;\n step: number;\n /** Characters of `text`. */\n chars: number;\n /** The replaced payload, verbatim. */\n text: string;\n /** Unix epoch milliseconds of the retention. */\n at: number;\n}\n\n/**\n * The JSON payload of one intervention record.\n *\n * Only losslessly serializable scalars: the record is read back by hosts and\n * humans, never replayed into a prompt. `feedback` is the model-facing text the\n * active path delivers — bounded on write, because it is the one field a caller\n * controls and an audit sink must not become a content dump. The four token\n * counters are the accounting contract: `potentialSavedTokens` is what the\n * candidate would have saved, `actualSavedTokens` what the harness really\n * stopped carrying, and the two are equal only in active mode.\n */\nexport interface InterventionAuditRecord {\n /** Capability that planned this action. */\n capability: string;\n /** The planned action name. */\n action: string;\n /** Effective three-state mode at plan time. */\n mode: string;\n /** Whether active mode actually executed the plan. */\n applied: boolean;\n /** Why it was planned, or why it was declined. */\n reason: string;\n /** Model-facing text the active path delivers; empty when none. */\n feedback: string;\n /** Judgment cost paid on this process' CPU (deterministic triggers, floors). */\n localLatencyMs: number;\n /** Judgment cost paid waiting for System 1. */\n remoteLatencyMs: number;\n /** Tokens the judgment itself cost (payload sent to the decision backend). */\n judgeTokens: number;\n /** Tokens of the payload this decision was about. */\n originalTokens: number;\n /** Tokens of the candidate the decision would install. */\n candidateTokens: number;\n /** Tokens the candidate would save; never counted as actual unless applied. */\n potentialSavedTokens: number;\n /** Tokens the harness actually stopped carrying because of this decision. */\n actualSavedTokens: number;\n /** Tokens this decision added to the model-visible surface. */\n injectedTokens: number;\n at: number;\n pattern?: string;\n confidence?: number;\n repeats?: number;\n digest?: string;\n floorApplied?: boolean;\n /** Whether the installed text carried the floor form; same value as `floorApplied`. */\n floored?: boolean;\n /**\n * Whether the installed reduction fell short of the floor's promised share.\n *\n * Present when a prune decision composed a reduction: `true` means the floor\n * form could not be built without growing past the original, so the judged\n * candidate itself was installed. This is the field that separates \"the\n * reduction was real but did not carry `pruneFloorRatio`\" from a real\n * `no-reduction` skip, where nothing was installed at all.\n */\n floorMissed?: boolean;\n /**\n * Whether a floor-missed install had to drop its locator marker.\n *\n * The marker is what tells a reader that a prune happened and where the full\n * payload lives. A candidate that fits only without it is still installed, and\n * this field records the omission instead of leaving it silent. Only ever\n * present with `floorMissed: true`.\n */\n markerOmitted?: boolean;\n memoHit?: boolean;\n agentId?: string;\n turn?: number;\n step?: number;\n /**\n * Why a plan was abandoned instead of planned, when it was.\n *\n * Present exactly on an `action: 'skip'` record: every branch that refuses to\n * plan writes one, so \"why no intervention\" is answerable from the session\n * log instead of a process-local counter. Equal to the record's `reason`,\n * kept as its own field so a reader can select skips without matching prose.\n */\n skip?: string;\n /** Which judging path produced the prune candidate. */\n judgePath?: 'segmented' | 'local' | 'fallback';\n /** Segments handed to System One by the prune judgment (0 when the local path ran). */\n judgedSegments?: number;\n /** Segments beyond the per-request limit, kept deterministically instead. */\n unjudgedSegments?: number;\n /** Segments the candidate the engine composed from kept whole. */\n keptSegments?: number;\n /** Characters of the aggressive-budget candidate the judgment built. */\n aggressiveChars?: number;\n /** Characters of the balanced-budget candidate the judgment built. */\n balancedChars?: number;\n /** Characters of the conservative-budget candidate the judgment built. */\n conservativeChars?: number;\n /** Segments System One really scored (`scores.size`); unreadable answers are absent. */\n scoredSegments?: number;\n /** Segments kept whole without a score: the unjudged safety margin. */\n autoKeptSegments?: number;\n /** Answers returned for a judged segment that carried no usable keep score. */\n unparsedScoreAnswers?: number;\n /** Characters of the payload this decision was about. */\n originalChars?: number;\n /** Characters of the candidate the decision would have installed. */\n candidateChars?: number;\n /** Why the segmented judge fell back to the local candidates, when it did. */\n fallbackReason?: string;\n /**\n * Locator of the controlled copy of the payload this decision replaced.\n *\n * Present exactly when a prune installed a replacement *and* the pre-prune\n * original was durably retained first; absent for every other decision and for\n * a prune that failed open. The locator resolves through\n * {@link readPrunedOriginal}, so the model-visible replacement can always be\n * checked against the bytes it stands in for.\n */\n originalLocator?: string;\n}\n\n/**\n * The JSON payload of one effort record. Deliberately narrower than\n * {@link ReflexEffortStatus}: only losslessly serializable fields, and `applied`\n * is `null` rather than absent when nothing was sent, so a reader never has to\n * tell \"cleared\" from \"field dropped by the serializer\".\n */\nexport interface EffortAuditRecord {\n /** Decided level. */\n level: string;\n /** Effort the rewritten request carried; `null` when the key was cleared. */\n applied: string | null;\n outcome: string;\n trigger: string;\n source: string;\n confidence: number;\n latencyMs: number;\n provider: string;\n model: string;\n /** Status-bar rendering of this decision. */\n line: string;\n /** Unix epoch milliseconds of the decision. */\n at: number;\n agentId?: string;\n role?: string;\n delegationDepth?: number;\n turn?: number;\n step?: number;\n basis?: string[];\n degradedReason?: string;\n task?: string;\n /** Provider the request named before routing. */\n requestedProvider?: string;\n /** Model the request named before routing. */\n requestedModel?: string;\n /** Whether routing moved the request onto another provider/model. */\n switched?: boolean;\n /** Whether the model was held to defend upstream prompt-cache affinity. */\n heldForCache?: boolean;\n /** Effort ids the routed model declared; `[]` when it declares none. */\n supportedEfforts?: string[];\n}\n\n/**\n * Project one status onto the audit payload.\n * @param status - the published effort status.\n * @returns the record payload.\n */\nexport function toEffortAuditRecord(status: ReflexEffortStatus): EffortAuditRecord {\n return {\n level: status.level,\n applied: status.applied ?? null,\n outcome: status.outcome,\n trigger: status.trigger,\n source: status.source,\n confidence: status.confidence,\n latencyMs: status.latencyMs,\n provider: status.provider,\n model: status.model,\n line: status.line,\n at: status.at,\n ...(status.agentId === undefined ? {} : { agentId: status.agentId }),\n ...(status.role === undefined ? {} : { role: status.role }),\n ...(status.delegationDepth === undefined ? {} : { delegationDepth: status.delegationDepth }),\n ...(status.turn === undefined ? {} : { turn: status.turn }),\n ...(status.step === undefined ? {} : { step: status.step }),\n ...(status.basis === undefined ? {} : { basis: status.basis }),\n ...(status.degradedReason === undefined ? {} : { degradedReason: status.degradedReason }),\n ...(status.task === undefined ? {} : { task: status.task }),\n ...(status.requestedProvider === undefined ? {} : { requestedProvider: status.requestedProvider }),\n ...(status.requestedModel === undefined ? {} : { requestedModel: status.requestedModel }),\n ...(status.switched === undefined ? {} : { switched: status.switched }),\n ...(status.heldForCache === undefined ? {} : { heldForCache: status.heldForCache }),\n ...(status.supportedEfforts === undefined ? {} : { supportedEfforts: status.supportedEfforts })\n };\n}\n\n/**\n * Append one effort decision to a Session's log.\n *\n * Best-effort by contract: an audit record is never allowed to fail a turn, so a\n * missing session (synthetic agent), a re-entrant append, or a rejected payload\n * is swallowed and reported as `undefined`.\n *\n * @param session - the requesting agent's session, when it has one.\n * @param status - the decision to record.\n * @returns the committed sequence number, or `undefined` when nothing was written.\n */\nexport function appendEffortRecord(session: unknown, status: ReflexEffortStatus): number | undefined {\n const target = session as Session | undefined;\n if (!target || typeof appendPluginRecord !== 'function') return undefined;\n try {\n return appendPluginRecord(target, EFFORT_RECORD_TYPE, toEffortAuditRecord(status)) as unknown as number;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Read back the effort decisions of one Session log.\n * @param events - the session log, or any slice of it.\n * @returns the validated records, oldest first; malformed payloads are dropped.\n */\nexport function effortRecordsOf(events: readonly SessionEvent[] | undefined): EffortAuditRecord[] {\n const records: EffortAuditRecord[] = [];\n for (const event of events ?? []) {\n let record;\n try {\n record = pluginRecordOf(event);\n } catch {\n continue;\n }\n if (!record || record.type !== EFFORT_RECORD_TYPE) continue;\n if (isEffortAuditRecord(record.data)) records.push(record.data);\n }\n return records;\n}\n\n/**\n * Validate one restored payload before a reader trusts it.\n * @param data - the payload committed by an earlier build.\n * @returns whether it carries the fields this plugin writes.\n */\nexport function isEffortAuditRecord(data: unknown): data is EffortAuditRecord {\n if (typeof data !== 'object' || data === null) return false;\n const record = data as Partial<EffortAuditRecord>;\n return (\n typeof record.level === 'string' &&\n typeof record.outcome === 'string' &&\n typeof record.trigger === 'string' &&\n typeof record.source === 'string' &&\n typeof record.confidence === 'number' &&\n typeof record.latencyMs === 'number' &&\n typeof record.provider === 'string' &&\n typeof record.model === 'string' &&\n typeof record.line === 'string' &&\n typeof record.at === 'number' &&\n (record.applied === null || typeof record.applied === 'string')\n );\n}\n\n/**\n * The JSON payload of one delegated-agent effort downgrade.\n *\n * Deliberately one record per *decision*, not per request: a child session may\n * see its selection re-emitted several times, and only a change of outcome is\n * news. `applied: null` means the marker was removed outright (the adapter's own\n * default), which is a real outcome and must not look like a missing field.\n */\nexport interface EffortInheritAuditRecord {\n /** The marker the deployment configured on the delegated agent (`reflex`/`auto`). */\n requested: string;\n /** The level the child now uses; `null` when the marker was removed. */\n applied: string | null;\n /**\n * Why the delegation could not decide: `reflex`/`auto` is a per-turn\n * System 1 decision taken inside the request waterfall, while a delegated\n * step's effort is fixed before that waterfall runs.\n */\n reason: 'subagent-cannot-decide';\n /** The parent level that was copied; absent when the parent had none. */\n inherited?: string;\n /** Whether the parent had a recorded selection at all. */\n parentLevel: 'present' | 'absent' | 'unreadable';\n /** Provider/model of the child selection carrying the marker. */\n provider: string;\n model: string;\n /** Human-readable, one line: what was configured and what it became. */\n line: string;\n /** Unix epoch milliseconds of the rewrite. */\n at: number;\n agentId?: string;\n delegationDepth?: number;\n}\n\n/**\n * Append one delegated-agent effort downgrade to a Session's log.\n *\n * Best-effort by the same contract as every other audit record here: a missing\n * session (synthetic agent) or a rejected payload is swallowed and reported as\n * `undefined`, never allowed to fail a turn.\n * @param session - the delegated agent's session, when it has one.\n * @param record - the rewrite to record.\n * @returns the committed sequence number, or `undefined` when nothing was written.\n */\nexport function appendEffortInheritRecord(session: unknown, record: EffortInheritAuditRecord): number | undefined {\n const target = session as Session | undefined;\n if (!target || typeof appendPluginRecord !== 'function') return undefined;\n try {\n return appendPluginRecord(target, EFFORT_INHERIT_RECORD_TYPE, record) as unknown as number;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Read back the delegated-agent effort downgrades of one Session log.\n * @param events - the session log, or any slice of it.\n * @returns the validated records, oldest first; malformed payloads are dropped.\n */\nexport function effortInheritRecordsOf(events: readonly SessionEvent[] | undefined): EffortInheritAuditRecord[] {\n const records: EffortInheritAuditRecord[] = [];\n for (const event of events ?? []) {\n let record;\n try {\n record = pluginRecordOf(event);\n } catch {\n continue;\n }\n if (!record || record.type !== EFFORT_INHERIT_RECORD_TYPE) continue;\n if (isEffortInheritAuditRecord(record.data)) records.push(record.data);\n }\n return records;\n}\n\n/**\n * Validate one restored downgrade payload before a reader trusts it.\n * @param data - the payload committed by an earlier build.\n * @returns whether it carries the fields this plugin writes.\n */\nexport function isEffortInheritAuditRecord(data: unknown): data is EffortInheritAuditRecord {\n if (typeof data !== 'object' || data === null) return false;\n const record = data as Partial<EffortInheritAuditRecord>;\n return (\n typeof record.requested === 'string' &&\n (record.applied === null || typeof record.applied === 'string') &&\n record.reason === 'subagent-cannot-decide' &&\n (record.parentLevel === 'present' || record.parentLevel === 'absent' || record.parentLevel === 'unreadable') &&\n typeof record.provider === 'string' &&\n typeof record.model === 'string' &&\n typeof record.line === 'string' &&\n typeof record.at === 'number'\n );\n}\n\n/**\n * Append one intervention decision to a Session's log.\n *\n * Best-effort, exactly like the effort audit: a missing session (synthetic\n * agent) or a rejected payload must never fail a turn, so failures are\n * swallowed and reported as `undefined`.\n *\n * @param session - the deciding agent's session, when it has one.\n * @param record - the decision to record.\n * @returns the committed sequence number, or `undefined` when nothing was written.\n */\nexport function appendInterventionRecord(session: unknown, record: InterventionAuditRecord): number | undefined {\n const target = session as Session | undefined;\n if (!target || typeof appendPluginRecord !== 'function') return undefined;\n try {\n return appendPluginRecord(target, INTERVENTION_RECORD_TYPE, boundRecord(record)) as unknown as number;\n } catch {\n return undefined;\n }\n}\n\n/** Longest `feedback` text one audit record may carry, in characters. */\nexport const INTERVENTION_FEEDBACK_MAX_CHARS = 600;\n\n/**\n * Bound the one caller-controlled field before it reaches the durable log.\n * @param record - the freshly built record.\n * @returns a copy whose `feedback` fits the audit budget.\n */\nfunction boundRecord(record: InterventionAuditRecord): InterventionAuditRecord {\n if (record.feedback.length <= INTERVENTION_FEEDBACK_MAX_CHARS) return record;\n return { ...record, feedback: `${record.feedback.slice(0, INTERVENTION_FEEDBACK_MAX_CHARS)}…` };\n}\n\n/**\n * Read back the intervention decisions of one Session log.\n * @param events - the session log, or any slice of it.\n * @returns the validated records, oldest first; malformed payloads are dropped.\n */\nexport function interventionRecordsOf(events: readonly SessionEvent[] | undefined): InterventionAuditRecord[] {\n const records: InterventionAuditRecord[] = [];\n for (const event of events ?? []) {\n let record;\n try {\n record = pluginRecordOf(event);\n } catch {\n continue;\n }\n if (!record || record.type !== INTERVENTION_RECORD_TYPE) continue;\n if (isInterventionAuditRecord(record.data)) records.push(record.data);\n }\n return records;\n}\n\n/**\n * Validate one restored intervention payload before a reader trusts it.\n * @param data - the payload committed by an earlier build.\n * @returns whether it carries the fields this plugin writes.\n */\nexport function isInterventionAuditRecord(data: unknown): data is InterventionAuditRecord {\n if (typeof data !== 'object' || data === null) return false;\n const record = data as Partial<InterventionAuditRecord>;\n return (\n typeof record.capability === 'string' &&\n typeof record.action === 'string' &&\n typeof record.mode === 'string' &&\n typeof record.applied === 'boolean' &&\n typeof record.reason === 'string' &&\n typeof record.feedback === 'string' &&\n typeof record.originalTokens === 'number' &&\n typeof record.candidateTokens === 'number' &&\n typeof record.potentialSavedTokens === 'number' &&\n typeof record.actualSavedTokens === 'number' &&\n typeof record.injectedTokens === 'number' &&\n typeof record.at === 'number'\n );\n}\n\n// ── controlled retention of a pre-prune payload ─────────────────────────────\n\n/**\n * The locator of one payload's retained copy.\n *\n * Derived from the payload's own digest, never from a log offset: a session that\n * is forked, resumed, or re-opened under a new store keeps the same locator for\n * the same payload, while an offset would silently point at another event. The\n * length is fixed, so a replacement can publish the locator without changing\n * size between the observation and the application of the same plan.\n * @param digest - the payload's {@link digestOf} identity.\n * @returns the locator string the replacement carries.\n */\nexport function pruneLocator(digest: string): string {\n return `${PRUNED_ORIGINAL_RECORD_TYPE}#${digest}`;\n}\n\n/** What the engine asks the log to retain before it replaces a payload. */\nexport interface PrunedOriginalRequest {\n /** Payload identity, as the prune decision computed it. */\n digest: string;\n /** Identity and name of the call whose result is about to shrink. */\n callId: string;\n tool: string;\n /** Turn and step of the replacement. */\n turn: number;\n step: number;\n /** The payload verbatim, as the reduction is about to replace it. */\n text: string;\n /** Clock seam; defaults to `Date.now()`. */\n at?: number;\n}\n\n/**\n * Retain one pre-prune payload in a Session's log, and prove that it landed.\n *\n * The read-back is the point of this function. An append that throws, a Session\n * that is not there, and a log that acknowledged a record it did not commit all\n * end the same way for the caller: `undefined`, meaning *the original is not\n * retrievable*, which the engine treats as a reason not to replace anything. A\n * reduction that cannot be checked against its original is worse than no\n * reduction, so this is deliberately fail-closed for the caller while remaining\n * best-effort towards the log.\n *\n * @param session - the deciding agent's session, when it has one.\n * @param request - the payload and its identity.\n * @returns the locator and the committed sequence, or `undefined` when nothing verifiable was written.\n */\nexport function appendPrunedOriginal(\n session: unknown,\n request: PrunedOriginalRequest\n): { locator: string; seq?: number } | undefined {\n const target = session as Session | undefined;\n if (!target || typeof appendPluginRecord !== 'function') return undefined;\n const locator = pruneLocator(request.digest);\n try {\n const record: PrunedOriginalRecord = {\n locator,\n digest: request.digest,\n callId: request.callId,\n tool: request.tool,\n turn: request.turn,\n step: request.step,\n chars: request.text.length,\n text: request.text,\n at: request.at ?? Date.now()\n };\n const seq = appendPluginRecord(target, PRUNED_ORIGINAL_RECORD_TYPE, record) as unknown as number;\n if (!verifiedRetention(target, seq, record)) return undefined;\n return { locator, seq };\n } catch {\n // An unretainable payload is never replaced; the caller fails open.\n return undefined;\n }\n}\n\n/**\n * Whether the committed log really carries the record we just appended.\n * @param session - the session that acknowledged the append.\n * @param seq - the acknowledged sequence number.\n * @param record - the record to find there.\n * @returns whether the log returns it verbatim.\n */\nfunction verifiedRetention(session: Session, seq: number, record: PrunedOriginalRecord): boolean {\n const reader = session as unknown as { eventAt?: (seq: unknown) => SessionEvent | undefined };\n const eventAt = reader.eventAt;\n if (typeof eventAt !== 'function' || !Number.isFinite(seq)) return false;\n const event = eventAt.call(session, seq);\n if (!event) return false;\n const committed = pluginRecordOf(event);\n if (!committed || committed.type !== PRUNED_ORIGINAL_RECORD_TYPE) return false;\n const data = committed.data as Partial<PrunedOriginalRecord> | undefined;\n return data?.digest === record.digest && data.text === record.text && data.chars === record.chars;\n}\n\n/**\n * Read back the retained payloads of one Session log.\n * @param events - the session log, or any slice of it.\n * @returns the validated records, oldest first; malformed payloads are dropped.\n */\nexport function prunedOriginalsOf(events: readonly SessionEvent[] | undefined): PrunedOriginalRecord[] {\n const records: PrunedOriginalRecord[] = [];\n for (const event of events ?? []) {\n let record;\n try {\n record = pluginRecordOf(event);\n } catch {\n continue;\n }\n if (!record || record.type !== PRUNED_ORIGINAL_RECORD_TYPE) continue;\n if (isPrunedOriginalRecord(record.data)) records.push(record.data);\n }\n return records;\n}\n\n/**\n * Resolve one locator against a Session log.\n *\n * A locator names a payload, not a position, so the same payload pruned twice in\n * one session has two records under one locator: the most recent one is returned,\n * which is the copy the live replacement was built beside.\n * @param events - the session log, or any slice of it.\n * @param locator - the locator the replacement published.\n * @returns the retained payload, or `undefined` when this log does not carry it.\n */\nexport function readPrunedOriginal(\n events: readonly SessionEvent[] | undefined,\n locator: string\n): PrunedOriginalRecord | undefined {\n let found: PrunedOriginalRecord | undefined;\n for (const record of prunedOriginalsOf(events)) {\n if (record.locator === locator) found = record;\n }\n return found;\n}\n\n/**\n * Validate one restored retention payload before a reader trusts it.\n * @param data - the payload committed by an earlier build.\n * @returns whether it carries the fields this plugin writes.\n */\nexport function isPrunedOriginalRecord(data: unknown): data is PrunedOriginalRecord {\n if (typeof data !== 'object' || data === null) return false;\n const record = data as Partial<PrunedOriginalRecord>;\n return (\n typeof record.locator === 'string' &&\n typeof record.digest === 'string' &&\n typeof record.callId === 'string' &&\n typeof record.tool === 'string' &&\n typeof record.turn === 'number' &&\n typeof record.step === 'number' &&\n typeof record.chars === 'number' &&\n typeof record.text === 'string' &&\n record.text.length === record.chars &&\n typeof record.at === 'number'\n );\n}\n"]}
@@ -0,0 +1,114 @@
1
+ /** Longest a probe may take, whatever the profile asks for. */
2
+ export declare const PROBE_TIMEOUT_MAX_MS = 15000;
3
+ /** Shortest accepted probe timeout; below this a healthy gateway looks like a timeout. */
4
+ export declare const PROBE_TIMEOUT_MIN_MS = 250;
5
+ /**
6
+ * The outcome classes a probe distinguishes.
7
+ *
8
+ * Four states, because they map onto four different user actions:
9
+ * `ok` → nothing to do; `auth-failed` → the key is wrong; `unreachable` → the
10
+ * address (or this machine's network) is wrong; `timeout` → the gateway is slow
11
+ * or the limit is too tight; `bad-response` → something speaks HTTP there but
12
+ * not the protocol this plugin expects; `misconfigured` → the plugin cannot even
13
+ * build a request (no URL for the backend type it resolved).
14
+ */
15
+ export type ProbeStatus = 'ok' | 'auth-failed' | 'unreachable' | 'timeout' | 'bad-response' | 'misconfigured' | 'model-unusable';
16
+ /** What one probe answers. */
17
+ export interface ProbeResult {
18
+ ok: boolean;
19
+ status: ProbeStatus;
20
+ /** Real round-trip time from request start to response headers, or the elapsed time of the failure. */
21
+ latencyMs: number;
22
+ /** HTTP status, when a response arrived. */
23
+ httpStatus?: number;
24
+ /** Redacted, single-line explanation. Never contains the key or the header. */
25
+ detail?: string;
26
+ /** Model the probe asked for. */
27
+ model?: string;
28
+ /** Endpoint that was contacted. Contains no credentials (URLs are checked). */
29
+ endpoint?: string;
30
+ }
31
+ /** The connection facts one probe needs: a projected profile, never the whole config. */
32
+ export interface ProbeTarget {
33
+ /** Profile name, for the detail line only. */
34
+ name: string;
35
+ backend: string;
36
+ baseUrl?: string;
37
+ model?: string;
38
+ apiKeyEnv?: string;
39
+ /** The key to present; read by this module and never returned. */
40
+ apiKey?: string;
41
+ timeoutMs?: number;
42
+ /**
43
+ * This connection's model cannot be sent (g-066 att-002), so there is nothing
44
+ * honest to test: the probe reports it instead of guessing a model. Only ever
45
+ * set, never inferred — a target without it carries the model it means.
46
+ */
47
+ modelUnusable?: boolean;
48
+ }
49
+ /** Options of one probe. */
50
+ export interface ProbeOptions {
51
+ /** Environment the `apiKeyEnv` indirection reads. */
52
+ env?: Record<string, string | undefined>;
53
+ /** `fetch` seam for tests. */
54
+ fetch?: typeof fetch;
55
+ /** Clock seam for tests. */
56
+ now?: () => number;
57
+ /** Signal that cancels the probe (panel closed, route disposed). */
58
+ signal?: AbortSignal;
59
+ }
60
+ /** What one endpoint probe sends. */
61
+ export interface ProbeRequestSpec {
62
+ url: string;
63
+ method: 'POST';
64
+ /** Authorization header value, or `undefined` when no key is configured. */
65
+ authorization?: string;
66
+ body: string;
67
+ timeoutMs: number;
68
+ }
69
+ /**
70
+ * Remove every credential-shaped substring from one diagnostic line.
71
+ *
72
+ * Belt and braces: callers are expected never to put a key in a detail string in
73
+ * the first place, and this makes an accidental one invisible rather than
74
+ * broadcast. It also flattens newlines so a gateway's multi-line error page
75
+ * cannot break the panel's single-line rendering.
76
+ *
77
+ * @param text - raw text, possibly from a remote server.
78
+ * @param secrets - values that must not appear (the key, the header value).
79
+ * @returns the sanitized single-line text.
80
+ */
81
+ export declare function redact(text: string, secrets?: readonly (string | undefined)[]): string;
82
+ /**
83
+ * Build the request one probe sends for a target.
84
+ *
85
+ * Exported so the endpoint's shape is pinned by a test rather than reimplemented
86
+ * in a stub server's expectations.
87
+ * @param target - the projected profile.
88
+ * @param env - environment the `apiKeyEnv` indirection reads.
89
+ * @returns the request spec, or a `status` describing why none can be built.
90
+ */
91
+ export declare function buildProbeRequest(target: ProbeTarget, env?: Record<string, string | undefined>): {
92
+ spec: ProbeRequestSpec;
93
+ } | {
94
+ status: ProbeStatus;
95
+ detail: string;
96
+ };
97
+ /**
98
+ * Clamp one profile's timeout onto the probe's accepted range.
99
+ * @param timeoutMs - authored per-request timeout.
100
+ * @returns a bounded timeout.
101
+ */
102
+ export declare function clampTimeout(timeoutMs: number | undefined): number;
103
+ /**
104
+ * Probe one System One connection.
105
+ *
106
+ * Never throws: every failure is classified, because a test button that reports
107
+ * "the handler threw" is less useful than one that reports "timed out after
108
+ * 8000 ms".
109
+ *
110
+ * @param target - the projected profile to test.
111
+ * @param options - environment, seams, and a cancellation signal.
112
+ * @returns the classified result, with bounded latency and redacted detail.
113
+ */
114
+ export declare function probeSystemOne(target: ProbeTarget, options?: ProbeOptions): Promise<ProbeResult>;