ai4ai 0.0.3 → 0.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/README.md +6 -0
  2. package/README.zh-CN.md +6 -0
  3. package/claude-plugin/.claude-plugin/plugin.json +1 -1
  4. package/claude-plugin/dist/adapters/claude/adapter.d.ts +10 -1
  5. package/claude-plugin/dist/adapters/claude/adapter.js +35 -10
  6. package/claude-plugin/dist/adapters/claude/journal.d.ts +8 -0
  7. package/claude-plugin/dist/adapters/claude/journal.js +4 -1
  8. package/claude-plugin/dist/adapters/claude/plugin.js +198 -91
  9. package/claude-plugin/dist/adapters/claude/worker.js +30 -8
  10. package/claude-plugin/dist/adapters/codex/adapter.d.ts +26 -19
  11. package/claude-plugin/dist/adapters/codex/adapter.js +283 -187
  12. package/claude-plugin/dist/adapters/codex/app-server.js +1 -1
  13. package/claude-plugin/dist/adapters/codex/control.d.ts +36 -1
  14. package/claude-plugin/dist/adapters/codex/control.js +74 -4
  15. package/claude-plugin/dist/adapters/codex/native-handoff.d.ts +60 -0
  16. package/claude-plugin/dist/adapters/codex/native-handoff.js +138 -0
  17. package/claude-plugin/dist/adapters/codex/runner.js +35 -32
  18. package/claude-plugin/dist/adapters/codex/tui-daemon-watch.js +60 -49
  19. package/claude-plugin/dist/adapters/declarations.d.ts +0 -1
  20. package/claude-plugin/dist/adapters/declarations.js +0 -1
  21. package/claude-plugin/dist/adapters/dsh/adapter.d.ts +39 -2
  22. package/claude-plugin/dist/adapters/dsh/adapter.js +164 -37
  23. package/claude-plugin/dist/adapters/dsh/plugin.d.ts +3 -1
  24. package/claude-plugin/dist/adapters/dsh/plugin.js +33 -22
  25. package/claude-plugin/dist/adapters/executors.d.ts +25 -2
  26. package/claude-plugin/dist/adapters/executors.js +58 -4
  27. package/claude-plugin/dist/adapters/external.d.ts +21 -0
  28. package/claude-plugin/dist/adapters/external.js +128 -18
  29. package/claude-plugin/dist/adapters/opencode/adapter.d.ts +13 -2
  30. package/claude-plugin/dist/adapters/opencode/adapter.js +53 -10
  31. package/claude-plugin/dist/adapters/opencode/journal.d.ts +2 -0
  32. package/claude-plugin/dist/adapters/opencode/journal.js +8 -3
  33. package/claude-plugin/dist/adapters/opencode/plugin.js +2 -2
  34. package/claude-plugin/dist/adapters/supervisor.js +64 -20
  35. package/claude-plugin/dist/adapters/types.d.ts +7 -0
  36. package/claude-plugin/dist/contract/schema.d.ts +8 -17
  37. package/claude-plugin/dist/contract/schema.js +3 -4
  38. package/claude-plugin/dist/contract/states.d.ts +11 -0
  39. package/claude-plugin/dist/contract/states.js +9 -0
  40. package/claude-plugin/dist/contract/types.d.ts +3 -3
  41. package/claude-plugin/dist/contract/validate.js +24 -14
  42. package/claude-plugin/dist/contract/version.d.ts +1 -1
  43. package/claude-plugin/dist/contract/version.js +1 -1
  44. package/claude-plugin/dist/core/dsh-selection.d.ts +43 -0
  45. package/claude-plugin/dist/core/dsh-selection.js +78 -0
  46. package/claude-plugin/dist/core/handoff.d.ts +42 -0
  47. package/claude-plugin/dist/core/handoff.js +63 -0
  48. package/claude-plugin/dist/core/index.d.ts +2 -0
  49. package/claude-plugin/dist/core/index.js +1 -0
  50. package/claude-plugin/dist/core/operations.js +33 -1
  51. package/claude-plugin/dist/core/session-probe.js +11 -22
  52. package/claude-plugin/dist/core/store.d.ts +8 -3
  53. package/claude-plugin/dist/core/store.js +17 -3
  54. package/claude-plugin/request-schema.json +1 -2
  55. package/dist/adapters/claude/adapter.d.ts +10 -1
  56. package/dist/adapters/claude/adapter.js +35 -10
  57. package/dist/adapters/claude/journal.d.ts +8 -0
  58. package/dist/adapters/claude/journal.js +4 -1
  59. package/dist/adapters/claude/plugin.js +198 -91
  60. package/dist/adapters/claude/worker.js +30 -8
  61. package/dist/adapters/codex/adapter.d.ts +26 -19
  62. package/dist/adapters/codex/adapter.js +283 -187
  63. package/dist/adapters/codex/app-server.js +1 -1
  64. package/dist/adapters/codex/control.d.ts +36 -1
  65. package/dist/adapters/codex/control.js +74 -4
  66. package/dist/adapters/codex/native-handoff.d.ts +60 -0
  67. package/dist/adapters/codex/native-handoff.js +138 -0
  68. package/dist/adapters/codex/runner.js +35 -32
  69. package/dist/adapters/codex/tui-daemon-watch.js +60 -49
  70. package/dist/adapters/declarations.d.ts +0 -1
  71. package/dist/adapters/declarations.js +0 -1
  72. package/dist/adapters/dsh/adapter.d.ts +39 -2
  73. package/dist/adapters/dsh/adapter.js +164 -37
  74. package/dist/adapters/dsh/plugin.d.ts +3 -1
  75. package/dist/adapters/dsh/plugin.js +33 -22
  76. package/dist/adapters/executors.d.ts +25 -2
  77. package/dist/adapters/executors.js +58 -4
  78. package/dist/adapters/external.d.ts +21 -0
  79. package/dist/adapters/external.js +128 -18
  80. package/dist/adapters/opencode/adapter.d.ts +13 -2
  81. package/dist/adapters/opencode/adapter.js +53 -10
  82. package/dist/adapters/opencode/journal.d.ts +2 -0
  83. package/dist/adapters/opencode/journal.js +8 -3
  84. package/dist/adapters/opencode/plugin.js +2 -2
  85. package/dist/adapters/supervisor.js +64 -20
  86. package/dist/adapters/types.d.ts +7 -0
  87. package/dist/contract/schema.d.ts +8 -17
  88. package/dist/contract/schema.js +3 -4
  89. package/dist/contract/states.d.ts +11 -0
  90. package/dist/contract/states.js +9 -0
  91. package/dist/contract/types.d.ts +3 -3
  92. package/dist/contract/validate.js +24 -14
  93. package/dist/contract/version.d.ts +1 -1
  94. package/dist/contract/version.js +1 -1
  95. package/dist/core/dsh-selection.d.ts +43 -0
  96. package/dist/core/dsh-selection.js +78 -0
  97. package/dist/core/handoff.d.ts +42 -0
  98. package/dist/core/handoff.js +63 -0
  99. package/dist/core/index.d.ts +2 -0
  100. package/dist/core/index.js +1 -0
  101. package/dist/core/operations.js +33 -1
  102. package/dist/core/session-probe.js +11 -22
  103. package/dist/core/store.d.ts +8 -3
  104. package/dist/core/store.js +17 -3
  105. package/docs/contract.md +25 -15
  106. package/opencode-plugin/dist/adapters/claude/adapter.d.ts +10 -1
  107. package/opencode-plugin/dist/adapters/claude/adapter.js +35 -10
  108. package/opencode-plugin/dist/adapters/claude/journal.d.ts +8 -0
  109. package/opencode-plugin/dist/adapters/claude/journal.js +4 -1
  110. package/opencode-plugin/dist/adapters/claude/plugin.js +198 -91
  111. package/opencode-plugin/dist/adapters/claude/worker.js +30 -8
  112. package/opencode-plugin/dist/adapters/codex/adapter.d.ts +26 -19
  113. package/opencode-plugin/dist/adapters/codex/adapter.js +283 -187
  114. package/opencode-plugin/dist/adapters/codex/app-server.js +1 -1
  115. package/opencode-plugin/dist/adapters/codex/control.d.ts +36 -1
  116. package/opencode-plugin/dist/adapters/codex/control.js +74 -4
  117. package/opencode-plugin/dist/adapters/codex/native-handoff.d.ts +60 -0
  118. package/opencode-plugin/dist/adapters/codex/native-handoff.js +138 -0
  119. package/opencode-plugin/dist/adapters/codex/runner.js +35 -32
  120. package/opencode-plugin/dist/adapters/codex/tui-daemon-watch.js +60 -49
  121. package/opencode-plugin/dist/adapters/declarations.d.ts +0 -1
  122. package/opencode-plugin/dist/adapters/declarations.js +0 -1
  123. package/opencode-plugin/dist/adapters/dsh/adapter.d.ts +39 -2
  124. package/opencode-plugin/dist/adapters/dsh/adapter.js +164 -37
  125. package/opencode-plugin/dist/adapters/dsh/plugin.d.ts +3 -1
  126. package/opencode-plugin/dist/adapters/dsh/plugin.js +33 -22
  127. package/opencode-plugin/dist/adapters/executors.d.ts +25 -2
  128. package/opencode-plugin/dist/adapters/executors.js +58 -4
  129. package/opencode-plugin/dist/adapters/external.d.ts +21 -0
  130. package/opencode-plugin/dist/adapters/external.js +128 -18
  131. package/opencode-plugin/dist/adapters/opencode/adapter.d.ts +13 -2
  132. package/opencode-plugin/dist/adapters/opencode/adapter.js +53 -10
  133. package/opencode-plugin/dist/adapters/opencode/journal.d.ts +2 -0
  134. package/opencode-plugin/dist/adapters/opencode/journal.js +8 -3
  135. package/opencode-plugin/dist/adapters/opencode/plugin.js +2 -2
  136. package/opencode-plugin/dist/adapters/supervisor.js +64 -20
  137. package/opencode-plugin/dist/adapters/types.d.ts +7 -0
  138. package/opencode-plugin/dist/contract/schema.d.ts +8 -17
  139. package/opencode-plugin/dist/contract/schema.js +3 -4
  140. package/opencode-plugin/dist/contract/states.d.ts +11 -0
  141. package/opencode-plugin/dist/contract/states.js +9 -0
  142. package/opencode-plugin/dist/contract/types.d.ts +3 -3
  143. package/opencode-plugin/dist/contract/validate.js +24 -14
  144. package/opencode-plugin/dist/contract/version.d.ts +1 -1
  145. package/opencode-plugin/dist/contract/version.js +1 -1
  146. package/opencode-plugin/dist/core/dsh-selection.d.ts +43 -0
  147. package/opencode-plugin/dist/core/dsh-selection.js +78 -0
  148. package/opencode-plugin/dist/core/handoff.d.ts +42 -0
  149. package/opencode-plugin/dist/core/handoff.js +63 -0
  150. package/opencode-plugin/dist/core/index.d.ts +2 -0
  151. package/opencode-plugin/dist/core/index.js +1 -0
  152. package/opencode-plugin/dist/core/operations.js +33 -1
  153. package/opencode-plugin/dist/core/session-probe.js +11 -22
  154. package/opencode-plugin/dist/core/store.d.ts +8 -3
  155. package/opencode-plugin/dist/core/store.js +17 -3
  156. package/opencode-plugin/package.json +1 -1
  157. package/package.json +1 -1
  158. package/claude-plugin/dist/adapters/codex/tui-restart-watch.d.ts +0 -2
  159. package/claude-plugin/dist/adapters/codex/tui-restart-watch.js +0 -330
  160. package/claude-plugin/dist/tmux/backend.d.ts +0 -55
  161. package/claude-plugin/dist/tmux/backend.js +0 -161
  162. package/dist/adapters/codex/tui-restart-watch.d.ts +0 -2
  163. package/dist/adapters/codex/tui-restart-watch.js +0 -330
  164. package/dist/tmux/backend.d.ts +0 -55
  165. package/dist/tmux/backend.js +0 -161
  166. package/opencode-plugin/dist/adapters/codex/tui-restart-watch.d.ts +0 -2
  167. package/opencode-plugin/dist/adapters/codex/tui-restart-watch.js +0 -330
  168. package/opencode-plugin/dist/tmux/backend.d.ts +0 -55
  169. package/opencode-plugin/dist/tmux/backend.js +0 -161
@@ -37,6 +37,17 @@ export declare function handoffOutcome(phase: string, options?: {
37
37
  };
38
38
  export declare const HANDOFF_MODES: readonly ["compact", "restart"];
39
39
  export type HandoffMode = typeof HANDOFF_MODES[number];
40
+ /**
41
+ * Proof mechanisms a current adapter may produce. `surface-replacement` is the
42
+ * zero-summary, same-session restart; `native-compaction` is the explicit
43
+ * compact opt-in where the harness summarized history. `new-session` is a
44
+ * legacy read-only value: historical journals may contain it, but no adapter
45
+ * produces it because a handoff must never change the session identity.
46
+ */
47
+ export declare const PROOF_MECHANISMS: readonly ["surface-replacement", "native-compaction"];
48
+ export type ProofMechanism = typeof PROOF_MECHANISMS[number];
49
+ export declare const LEGACY_PROOF_MECHANISM: "new-session";
50
+ export type StoredProofMechanism = ProofMechanism | typeof LEGACY_PROOF_MECHANISM;
40
51
  /**
41
52
  * `restart` is the default handoff mode: the new context contains only the
42
53
  * caller-supplied material, with no harness summary. `compact` remains an
@@ -54,6 +54,15 @@ export function handoffOutcome(phase, options = {}) {
54
54
  }
55
55
  }
56
56
  export const HANDOFF_MODES = ['compact', 'restart'];
57
+ /**
58
+ * Proof mechanisms a current adapter may produce. `surface-replacement` is the
59
+ * zero-summary, same-session restart; `native-compaction` is the explicit
60
+ * compact opt-in where the harness summarized history. `new-session` is a
61
+ * legacy read-only value: historical journals may contain it, but no adapter
62
+ * produces it because a handoff must never change the session identity.
63
+ */
64
+ export const PROOF_MECHANISMS = ['surface-replacement', 'native-compaction'];
65
+ export const LEGACY_PROOF_MECHANISM = 'new-session';
57
66
  /**
58
67
  * `restart` is the default handoff mode: the new context contains only the
59
68
  * caller-supplied material, with no harness summary. `compact` remains an
@@ -1,4 +1,4 @@
1
- import type { Availability, ContextVerification, HandoffMode, HandoffPhase, HarnessId, Isolation, LifecycleState, ModelVerification, Operation, Os, PercentSource, State, Surface, SourceLabel, AutoCompactSource } from './states.js';
1
+ import type { Availability, ContextVerification, HandoffMode, HandoffPhase, HarnessId, Isolation, LifecycleState, ModelVerification, Operation, Os, PercentSource, State, StoredProofMechanism, Surface, SourceLabel, AutoCompactSource } from './states.js';
2
2
  import type { Feature } from './version.js';
3
3
  /** Identity supplied exclusively by a trusted native integration, never by tool arguments. */
4
4
  export interface Identity {
@@ -82,7 +82,8 @@ export interface ContractError {
82
82
  export interface AdoptionProof {
83
83
  source: Identity;
84
84
  successor: Identity;
85
- mechanism: 'new-session' | 'surface-replacement';
85
+ /** Current adapters produce the first two; `new-session` is legacy read-only. */
86
+ mechanism: StoredProofMechanism;
86
87
  nativeEvidence: string;
87
88
  }
88
89
  export interface SessionPointer {
@@ -164,7 +165,6 @@ export interface CapabilityDeclaration {
164
165
  modelOverride: Availability;
165
166
  reasoningEffortOverride: Availability;
166
167
  crossSurface: Availability;
167
- tmuxFallback: 'off' | 'experimental';
168
168
  };
169
169
  spawn: {
170
170
  availability: Availability;
@@ -1,5 +1,5 @@
1
1
  import { FEATURES } from './version.js';
2
- import { AVAILABILITY, AUTOCOMPACT_SOURCES, CONTEXT_VERIFICATION, FIELD_STATE_KEYS, HANDOFF_MODES, HANDOFF_PHASES, HARNESSES, ISOLATION, LIFECYCLE_STATES, MODEL_VERIFICATION, OPERATIONS, OSES, PERCENT_SOURCE, SOURCE_LABELS, STATES, SURFACES, } from './states.js';
2
+ import { AVAILABILITY, AUTOCOMPACT_SOURCES, CONTEXT_VERIFICATION, FIELD_STATE_KEYS, HANDOFF_MODES, HANDOFF_PHASES, HARNESSES, ISOLATION, LEGACY_PROOF_MECHANISM, LIFECYCLE_STATES, MODEL_VERIFICATION, OPERATIONS, OSES, PERCENT_SOURCE, PROOF_MECHANISMS, SOURCE_LABELS, STATES, SURFACES, } from './states.js';
3
3
  const ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
4
4
  const object = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
5
5
  const text = (v, max) => typeof v === 'string' && v.trim().length > 0 && v.length <= max && !v.includes('\0');
@@ -207,8 +207,6 @@ export function validateCapability(value) {
207
207
  for (const key of ['modelOverride', 'reasoningEffortOverride', 'crossSurface'])
208
208
  if (!member(value.handoff[key], AVAILABILITY))
209
209
  issues.push(problem(`handoff.${key}`, 'schema', 'Unknown availability'));
210
- if (!member(value.handoff.tmuxFallback, ['off', 'experimental']))
211
- issues.push(problem('handoff.tmuxFallback', 'schema', 'Unknown tmux fallback declaration'));
212
210
  }
213
211
  else
214
212
  issues.push(problem('handoff', 'required', 'Expected handoff capabilities'));
@@ -398,17 +396,29 @@ export function validateResult(value) {
398
396
  // query completion is much weaker and needs none.
399
397
  if (value.status === 'completed' && value.operation === 'handoff' && (value.durable !== true || value.proof === undefined))
400
398
  issues.push(problem('proof', 'required', 'Completed handoff requires durable adoption proof'));
401
- if (value.status === 'completed' && value.operation === 'handoff' && object(value.proof)) {
402
- const source = validateIdentity(value.proof.source);
403
- const successor = validateIdentity(value.proof.successor);
404
- if (!source.ok)
405
- issues.push(...source.issues.map(p => ({ ...p, path: `proof.source.${p.path}` })));
406
- if (!successor.ok)
407
- issues.push(...successor.issues.map(p => ({ ...p, path: `proof.successor.${p.path}` })));
408
- if (!member(value.proof.mechanism, ['new-session', 'surface-replacement']))
409
- issues.push(problem('proof.mechanism', 'schema', 'Unknown handoff mechanism'));
410
- if (!text(value.proof.nativeEvidence, 4096))
411
- issues.push(problem('proof.nativeEvidence', 'schema', 'Expected native adoption evidence'));
399
+ // Any result carrying adoption proof is checked, not only `completed`: an
400
+ // `applied` result also claims the context was replaced. A current mechanism
401
+ // must keep the native session identity (a handoff never changes the SID);
402
+ // `new-session` is accepted only as legacy evidence written by older releases.
403
+ if (value.proof !== undefined) {
404
+ if (!object(value.proof))
405
+ issues.push(problem('proof', 'schema', 'Expected adoption proof'));
406
+ else {
407
+ const source = validateIdentity(value.proof.source);
408
+ const successor = validateIdentity(value.proof.successor);
409
+ if (!source.ok)
410
+ issues.push(...source.issues.map(p => ({ ...p, path: `proof.source.${p.path}` })));
411
+ if (!successor.ok)
412
+ issues.push(...successor.issues.map(p => ({ ...p, path: `proof.successor.${p.path}` })));
413
+ if (!member(value.proof.mechanism, [...PROOF_MECHANISMS, LEGACY_PROOF_MECHANISM]))
414
+ issues.push(problem('proof.mechanism', 'schema', 'Unknown handoff mechanism'));
415
+ if (!text(value.proof.nativeEvidence, 4096))
416
+ issues.push(problem('proof.nativeEvidence', 'schema', 'Expected native adoption evidence'));
417
+ if (member(value.proof.mechanism, PROOF_MECHANISMS) && source.ok && successor.ok
418
+ && source.value.session !== successor.value.session) {
419
+ issues.push(problem('proof.successor.session', 'same-session', 'A handoff must preserve the native session identity; use spawn for a new session'));
420
+ }
421
+ }
412
422
  }
413
423
  return done(value, issues);
414
424
  }
@@ -1,3 +1,3 @@
1
1
  /** Features a caller may require explicitly. Unknown names fail closed. */
2
- export declare const FEATURES: readonly ["handoff", "spawn", "status", "message", "cancel", "stop", "list", "surface-preserve", "surface-cross", "spawn-isolation", "spawn-policy", "model-override", "reasoning-effort-override", "tmux-fallback"];
2
+ export declare const FEATURES: readonly ["handoff", "spawn", "status", "message", "cancel", "stop", "list", "surface-preserve", "surface-cross", "spawn-isolation", "spawn-policy", "model-override", "reasoning-effort-override"];
3
3
  export type Feature = typeof FEATURES[number];
@@ -2,5 +2,5 @@
2
2
  export const FEATURES = [
3
3
  'handoff', 'spawn', 'status', 'message', 'cancel', 'stop', 'list',
4
4
  'surface-preserve', 'surface-cross', 'spawn-isolation', 'spawn-policy',
5
- 'model-override', 'reasoning-effort-override', 'tmux-fallback',
5
+ 'model-override', 'reasoning-effort-override',
6
6
  ];
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Replica of the DSH session model-selection projection
3
+ * (`@deepseek-ai/dsh-agent` `lib/types/model-selection.js`,
4
+ * `modelSelectionProjectionDefinition`, stateVersion 3).
5
+ *
6
+ * Only two event types participate: `model/selection` records a pending choice
7
+ * and `request/header` records the route a request actually used, retiring a
8
+ * matching pending choice. The effective selection is `pending ?? lastUsed`.
9
+ * Title/compaction/context events never participate, which is why a
10
+ * `session/title-llm-request` effort (for example "off") can no longer
11
+ * overwrite the request header's effort.
12
+ *
13
+ * The fold is intentionally literal: an incomplete selection (missing provider
14
+ * or model) is ignored, an absent effort is its own value, and
15
+ * `adapterDefaults.reasoningEffort === true` means the header's effort was the
16
+ * adapter default and is therefore not a recorded selection.
17
+ */
18
+ export interface DshModelSelection {
19
+ provider: string;
20
+ model: string;
21
+ reasoningEffort?: string;
22
+ }
23
+ export interface DshSelectionState {
24
+ lastUsed: DshModelSelection | null;
25
+ pending: DshModelSelection | null;
26
+ }
27
+ export interface DshSelectionEvent {
28
+ type?: unknown;
29
+ data?: unknown;
30
+ }
31
+ /** Absent effort is a distinct value; provider, model and effort must all agree. */
32
+ export declare function sameDshSelection(left: DshModelSelection | null, right: DshModelSelection | null): boolean;
33
+ /** One fold step, mirroring the official `apply` function. */
34
+ export declare function applyDshSelection(state: DshSelectionState, event: DshSelectionEvent): DshSelectionState;
35
+ /** Fold an ordered event stream (oldest first) into the projection state. */
36
+ export declare function foldDshSelection(events: Iterable<DshSelectionEvent>): DshSelectionState;
37
+ /** The effective selection (`pending ?? lastUsed`), or null when the fold is empty. */
38
+ export declare function effectiveDshSelection(state: DshSelectionState): DshModelSelection | null;
39
+ /** Model id and reasoning effort from one fold, with no non-official fallback. */
40
+ export declare function dshSelectionValues(events: Iterable<DshSelectionEvent>): {
41
+ model: string | null;
42
+ reasoningEffort: string | null;
43
+ };
@@ -0,0 +1,78 @@
1
+ const text = (value) => typeof value === 'string' && value.length > 0 ? value : undefined;
2
+ /** A complete selection needs a provider and a model; effort is optional. */
3
+ function complete(value) {
4
+ if (!value || typeof value !== 'object')
5
+ return null;
6
+ const record = value;
7
+ const provider = text(record.provider);
8
+ const model = text(record.model);
9
+ if (!provider || !model)
10
+ return null;
11
+ const reasoningEffort = text(record.reasoningEffort);
12
+ return reasoningEffort === undefined ? { provider, model } : { provider, model, reasoningEffort };
13
+ }
14
+ /** Absent effort is a distinct value; provider, model and effort must all agree. */
15
+ export function sameDshSelection(left, right) {
16
+ if (left === right)
17
+ return true;
18
+ if (!left || !right)
19
+ return false;
20
+ return left.provider === right.provider && left.model === right.model && left.reasoningEffort === right.reasoningEffort;
21
+ }
22
+ /** Selection a recorded `request/header` used, omitting an adapter-defaulted effort. */
23
+ function selectionOfHeader(data) {
24
+ if (!data || typeof data !== 'object')
25
+ return null;
26
+ const header = data.header;
27
+ if (!header || typeof header !== 'object')
28
+ return null;
29
+ const record = header;
30
+ const config = record.config;
31
+ if (!config || typeof config !== 'object')
32
+ return null;
33
+ const settings = config;
34
+ const provider = text(settings.provider);
35
+ const model = text(settings.model);
36
+ if (!provider || !model)
37
+ return null;
38
+ const defaults = record.adapterDefaults && typeof record.adapterDefaults === 'object'
39
+ ? record.adapterDefaults
40
+ : undefined;
41
+ const reasoningEffort = defaults?.reasoningEffort === true ? undefined : text(settings.reasoningEffort);
42
+ return reasoningEffort === undefined ? { provider, model } : { provider, model, reasoningEffort };
43
+ }
44
+ const initialState = () => ({ lastUsed: null, pending: null });
45
+ /** One fold step, mirroring the official `apply` function. */
46
+ export function applyDshSelection(state, event) {
47
+ if (event.type === 'model/selection') {
48
+ const pending = complete(event.data);
49
+ if (!pending || sameDshSelection(state.pending, pending))
50
+ return state;
51
+ return { ...state, pending };
52
+ }
53
+ if (event.type !== 'request/header')
54
+ return state;
55
+ const lastUsed = selectionOfHeader(event.data);
56
+ if (!lastUsed)
57
+ return state;
58
+ const pending = sameDshSelection(state.pending, lastUsed) ? null : state.pending;
59
+ if (sameDshSelection(state.lastUsed, lastUsed) && pending === state.pending)
60
+ return state;
61
+ return { lastUsed, pending };
62
+ }
63
+ /** Fold an ordered event stream (oldest first) into the projection state. */
64
+ export function foldDshSelection(events) {
65
+ let state = initialState();
66
+ for (const event of events)
67
+ state = applyDshSelection(state, event);
68
+ return state;
69
+ }
70
+ /** The effective selection (`pending ?? lastUsed`), or null when the fold is empty. */
71
+ export function effectiveDshSelection(state) {
72
+ return state.pending ?? state.lastUsed;
73
+ }
74
+ /** Model id and reasoning effort from one fold, with no non-official fallback. */
75
+ export function dshSelectionValues(events) {
76
+ const selection = effectiveDshSelection(foldDshSelection(events));
77
+ return { model: selection?.model ?? null, reasoningEffort: selection?.reasoningEffort ?? null };
78
+ }
@@ -0,0 +1,42 @@
1
+ import type { AdoptionProof, Identity } from '../contract/types.js';
2
+ import type { NativeOutcome } from '../adapters/types.js';
3
+ import { type HandoffMode, type ProofMechanism, type StoredProofMechanism } from '../contract/states.js';
4
+ /**
5
+ * Handoff finalization shared by every adapter, journal and watcher.
6
+ *
7
+ * A current handoff never changes the native session identity: `restart`
8
+ * replaces the context in place and `compact` adds a native summary in place.
9
+ * The only way to obtain a fresh identity is `spawn`, so a produced proof whose
10
+ * successor session differs is a defect, never a success. `new-session` stays
11
+ * readable for journals written by older releases; those records are exempt
12
+ * from the same-session gate and are never produced again.
13
+ */
14
+ export declare const isProducedMechanism: (value: unknown) => value is ProofMechanism;
15
+ export declare const isLegacyMechanism: (value: unknown) => boolean;
16
+ /** Old records stored only the mode; this reproduces the mechanism they implied. */
17
+ export declare function legacyProofMechanism(mode: 'restart' | 'compact' | undefined): StoredProofMechanism;
18
+ /** Build adoption proof that is same-session by construction. */
19
+ export declare function sameSessionProof(source: Identity, generation: string, mechanism: ProofMechanism, nativeEvidence: string): AdoptionProof;
20
+ export interface HandoffFinalizeInput {
21
+ /** Proof carried by the outcome, if any. */
22
+ proof?: AdoptionProof;
23
+ /** Explicit field on the durable record; absent on pre-0.0.5 records. */
24
+ proofMechanism?: StoredProofMechanism;
25
+ /** Mode stored by a pre-0.0.5 record. */
26
+ mode?: HandoffMode;
27
+ }
28
+ export interface HandoffFinalizeResult {
29
+ /** True when the record predates the explicit proofMechanism field. */
30
+ legacy: boolean;
31
+ mechanism?: StoredProofMechanism | undefined;
32
+ error?: string | undefined;
33
+ }
34
+ /**
35
+ * Check a completion point. Adapters that build their own proof call this (or
36
+ * `sameSessionProof`) before returning; journals/watchers call it when applying
37
+ * a record so an old pending record is not mislabelled and a new one cannot
38
+ * silently change the session.
39
+ */
40
+ export declare function finalizeHandoff(input: HandoffFinalizeInput): HandoffFinalizeResult;
41
+ /** Fail-closed normalization: a mismatched proof becomes a structured failure. */
42
+ export declare function guardHandoffOutcome(outcome: NativeOutcome, input: HandoffFinalizeInput): NativeOutcome;
@@ -0,0 +1,63 @@
1
+ import { LEGACY_PROOF_MECHANISM, PROOF_MECHANISMS } from '../contract/states.js';
2
+ /**
3
+ * Handoff finalization shared by every adapter, journal and watcher.
4
+ *
5
+ * A current handoff never changes the native session identity: `restart`
6
+ * replaces the context in place and `compact` adds a native summary in place.
7
+ * The only way to obtain a fresh identity is `spawn`, so a produced proof whose
8
+ * successor session differs is a defect, never a success. `new-session` stays
9
+ * readable for journals written by older releases; those records are exempt
10
+ * from the same-session gate and are never produced again.
11
+ */
12
+ export const isProducedMechanism = (value) => typeof value === 'string' && PROOF_MECHANISMS.includes(value);
13
+ export const isLegacyMechanism = (value) => value === LEGACY_PROOF_MECHANISM;
14
+ /** Old records stored only the mode; this reproduces the mechanism they implied. */
15
+ export function legacyProofMechanism(mode) {
16
+ // Before 0.0.5, restart replaced the session (`/clear` or a new thread) and
17
+ // compact replaced the surface in place.
18
+ return mode === 'compact' ? 'surface-replacement' : LEGACY_PROOF_MECHANISM;
19
+ }
20
+ /** Build adoption proof that is same-session by construction. */
21
+ export function sameSessionProof(source, generation, mechanism, nativeEvidence) {
22
+ return { source, successor: { ...source, generation }, mechanism, nativeEvidence };
23
+ }
24
+ /**
25
+ * Check a completion point. Adapters that build their own proof call this (or
26
+ * `sameSessionProof`) before returning; journals/watchers call it when applying
27
+ * a record so an old pending record is not mislabelled and a new one cannot
28
+ * silently change the session.
29
+ */
30
+ export function finalizeHandoff(input) {
31
+ const explicit = input.proofMechanism;
32
+ const mechanism = explicit ?? input.proof?.mechanism ?? (input.mode ? legacyProofMechanism(input.mode) : undefined);
33
+ const legacy = explicit === undefined;
34
+ if (!input.proof)
35
+ return { legacy, ...(mechanism ? { mechanism } : {}) };
36
+ if (mechanism && isProducedMechanism(mechanism)
37
+ && input.proof.source.session !== input.proof.successor.session) {
38
+ return {
39
+ legacy, mechanism,
40
+ error: `A ${mechanism} handoff must preserve the native session identity (${input.proof.source.session} -> ${input.proof.successor.session}); use spawn for a new session`,
41
+ };
42
+ }
43
+ if (mechanism === LEGACY_PROOF_MECHANISM && isProducedMechanism(input.proof.mechanism)) {
44
+ // A record that says "legacy" cannot carry a newly produced mechanism;
45
+ // that would relabel old behaviour as a current guarantee.
46
+ return { legacy, mechanism, error: 'Legacy handoff records must keep their historical proof mechanism' };
47
+ }
48
+ return { legacy, mechanism };
49
+ }
50
+ /** Fail-closed normalization: a mismatched proof becomes a structured failure. */
51
+ export function guardHandoffOutcome(outcome, input) {
52
+ const finalized = finalizeHandoff({ ...input, ...(outcome.proof ? { proof: outcome.proof } : {}) });
53
+ if (!finalized.error)
54
+ return outcome;
55
+ return {
56
+ status: 'failed',
57
+ reason: finalized.error,
58
+ durable: outcome.durable ?? false,
59
+ state: 'failed',
60
+ unavailable: ['handoff.native'],
61
+ error: { code: 'handoff-session-mismatch', message: finalized.error },
62
+ };
63
+ }
@@ -5,3 +5,5 @@ export { activeRecord } from './journal.js';
5
5
  export { DEFAULT_POLICY, normalizePolicy, checkPolicy } from './policy.js';
6
6
  export { execute, currentOs, newExecutorId, ownedBy } from './operations.js';
7
7
  export type { OperationsOptions } from './operations.js';
8
+ export { finalizeHandoff, guardHandoffOutcome, isLegacyMechanism, isProducedMechanism, legacyProofMechanism, sameSessionProof, } from './handoff.js';
9
+ export type { HandoffFinalizeInput, HandoffFinalizeResult } from './handoff.js';
@@ -3,3 +3,4 @@ export { fingerprint, sameIdentity } from './fingerprint.js';
3
3
  export { activeRecord } from './journal.js';
4
4
  export { DEFAULT_POLICY, normalizePolicy, checkPolicy } from './policy.js';
5
5
  export { execute, currentOs, newExecutorId, ownedBy } from './operations.js';
6
+ export { finalizeHandoff, guardHandoffOutcome, isLegacyMechanism, isProducedMechanism, legacyProofMechanism, sameSessionProof, } from './handoff.js';
@@ -4,6 +4,7 @@ import { fingerprint } from './fingerprint.js';
4
4
  import { lifecycleOfStatus, pidAlive, readStatus } from '../adapters/executors.js';
5
5
  import { sessionPointer } from './session-probe.js';
6
6
  import { checkPolicy, ROOT_POLICY } from './policy.js';
7
+ import { guardHandoffOutcome } from './handoff.js';
7
8
  import { LockBusyError } from '../install/scope.js';
8
9
  const callerKey = (identity) => `${identity.harness}\0${identity.workspace}\0${identity.surface}\0${identity.session}\0${identity.agent}`;
9
10
  /** Ownership ignores generation so a session keeps its objects across its own handoff. */
@@ -93,6 +94,28 @@ async function executeInner(request, options) {
93
94
  durable: true, error: { code: 'idempotency-conflict', message: 'The operation id was already used with different input' },
94
95
  });
95
96
  }
97
+ // A pending handoff may have advanced in a native watcher or runner that
98
+ // cannot write the shared store itself. Ask the adapter for the current
99
+ // state instead of returning a stale pending result forever.
100
+ if (req.operation === 'handoff' && ['accepted', 'pending', 'applied'].includes(existing.status) && adapter.reconcileHandoff) {
101
+ try {
102
+ const reconciled = await adapter.reconcileHandoff(existing.request, ctx);
103
+ if (reconciled) {
104
+ const normalized = normalizeOutcome(existing.request, reconciled);
105
+ // The reconciled result is subject to the same contract check as a
106
+ // first response, including the same-session proof rule.
107
+ if (validateResult(normalized).ok) {
108
+ if (normalized.status !== existing.status) {
109
+ await store.completePending(existing.source, existing.request.operationId, normalized);
110
+ }
111
+ return normalized;
112
+ }
113
+ }
114
+ }
115
+ catch {
116
+ // Keep the durable pending record; never invent progress.
117
+ }
118
+ }
96
119
  return existing.result;
97
120
  }
98
121
  if (req.operation === 'capabilities') {
@@ -109,6 +132,13 @@ async function executeInner(request, options) {
109
132
  if (req.operation === 'handoff' && declared?.handoff.availability === 'unsupported') {
110
133
  return result(req, 'unsupported', `Adapter declares handoff unsupported on ${identity.surface}`, { unavailable: ['handoff'] });
111
134
  }
135
+ // Capability declarations decide mode availability, not just overall handoff
136
+ // availability: an undeclared `compact` must be refused explicitly.
137
+ if (req.operation === 'handoff' && req.mode !== undefined && declared && !declared.handoff.modes.includes(req.mode)) {
138
+ return result(req, 'unsupported', `Adapter does not declare the ${req.mode} handoff mode on ${identity.surface}; omit mode for the zero-summary restart`, {
139
+ unavailable: [`handoff.${req.mode}`],
140
+ });
141
+ }
112
142
  if (req.operation === 'spawn' && declared?.spawn.availability === 'unsupported') {
113
143
  return result(req, 'unsupported', `Adapter declares spawn unsupported on ${identity.surface}`, { unavailable: ['spawn'] });
114
144
  }
@@ -168,7 +198,9 @@ async function executeInner(request, options) {
168
198
  const message = error instanceof Error ? error.message : 'Adapter failed';
169
199
  outcome = { status: 'unknown', reason: `Native outcome is uncertain; reconcile before retrying: ${message}`, error: { code: 'native-unknown', message } };
170
200
  }
171
- const normalized = normalizeOutcome(req, outcome);
201
+ // One finalization point for every adapter: a produced proof that changed
202
+ // the native session becomes a structured failure, never a success.
203
+ const normalized = normalizeOutcome(req, guardHandoffOutcome(outcome, {}));
172
204
  const checked = validateResult(normalized);
173
205
  if (!checked.ok) {
174
206
  return result(req, 'failed', 'Adapter produced a result that violates the contract; nothing was journaled', {
@@ -3,6 +3,7 @@ import { open, readFile, readdir, stat } from 'node:fs/promises';
3
3
  import os from 'node:os';
4
4
  import path from 'node:path';
5
5
  import zlib from 'node:zlib';
6
+ import { dshSelectionValues } from './dsh-selection.js';
6
7
  const MAX_BYTES = 4 * 1024 * 1024;
7
8
  const SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,191}$/;
8
9
  /** Session ids come from harness output; reject anything that could escape a store path. */
@@ -177,33 +178,21 @@ export async function dshSessionUsage(workspace, sessionId, dshHome) {
177
178
  const declaredId = declared ? safeText(declared.sessionId ?? declared.id) : null;
178
179
  if (declaredId !== null && declaredId !== id)
179
180
  continue; // identity mismatch: never read another session
181
+ // Model and effort come from the official DSH projection only: a literal
182
+ // replica of `modelSelectionProjectionDefinition` (pending ?? lastUsed).
183
+ // Title/compaction/context events are excluded, so a title request's
184
+ // effort can never overwrite the request header (AI4AI-DSH-013).
185
+ const selection = dshSelectionValues(rows.map(row => ({
186
+ type: row.type,
187
+ data: row.data && typeof row.data === 'object' ? row.data : row,
188
+ })));
189
+ const model = selection.model;
190
+ const reasoningEffort = selection.reasoningEffort;
180
191
  let used = null;
181
- let model = null;
182
192
  let window = null;
183
- let reasoningEffort = null;
184
193
  for (const row of rows) {
185
194
  // DSH persists typed events under `data`; tolerate older flat shapes.
186
195
  const data = row.data && typeof row.data === 'object' ? row.data : row;
187
- const header = data.header && typeof data.header === 'object' ? data.header : undefined;
188
- const headerConfig = header?.config && typeof header.config === 'object' ? header.config : undefined;
189
- const route = data.route && typeof data.route === 'object' ? data.route : undefined;
190
- const source = data.source && typeof data.source === 'object' ? data.source : undefined;
191
- if (typeof data.model === 'string')
192
- model = data.model;
193
- else if (typeof headerConfig?.model === 'string')
194
- model = headerConfig.model;
195
- else if (typeof route?.model === 'string')
196
- model = route.model;
197
- else if (typeof source?.model?.model === 'string')
198
- model = source.model.model;
199
- else if (typeof row.model === 'string')
200
- model = row.model;
201
- if (typeof data.reasoningEffort === 'string')
202
- reasoningEffort = data.reasoningEffort;
203
- else if (typeof headerConfig?.reasoningEffort === 'string')
204
- reasoningEffort = headerConfig.reasoningEffort;
205
- else if (typeof source?.effort === 'string')
206
- reasoningEffort = source.effort;
207
196
  const usage = data.usage && typeof data.usage === 'object' ? data.usage
208
197
  : row.usage && typeof row.usage === 'object' ? row.usage : undefined;
209
198
  if (usage && typeof usage.inputTokens === 'number') {
@@ -29,6 +29,10 @@ export interface ExecutorRecord {
29
29
  policy: Required<Policy>;
30
30
  isolation: Isolation;
31
31
  sessionId?: string;
32
+ /** Effective model at spawn time, restored on resumed turns. */
33
+ model?: string;
34
+ /** Effective reasoning effort at spawn time, restored on resumed turns. */
35
+ reasoningEffort?: string;
32
36
  state: string;
33
37
  createdAt: string;
34
38
  carrier: CarrierInfo;
@@ -56,9 +60,10 @@ export declare class Ai4aiStore {
56
60
  append(record: OperationRecord): Promise<void>;
57
61
  /**
58
62
  * Complete a pending operation in place. Durable operations are normally
59
- * append-only; a detached native watcher (Codex TUI /new) is the one case
60
- * where the same operation advances after its first result, so the pending
61
- * record is replaced with the terminal one. Terminal records are never
63
+ * append-only; a detached native watcher is the one case where the same
64
+ * operation advances after its first result, so the pending record is
65
+ * replaced with the terminal one. The replacement is contract-checked
66
+ * (including the same-session proof rule) and terminal records are never
62
67
  * rewritten.
63
68
  */
64
69
  completePending(identity: Identity, operationId: string, outcome: Result): Promise<boolean>;
@@ -2,6 +2,8 @@ import path from 'node:path';
2
2
  import { createHash } from 'node:crypto';
3
3
  import { mkdir, lstat } from 'node:fs/promises';
4
4
  import { atomicJson, bytes, contained, digest, ownership, selectedRoot, withScopeLock } from '../install/scope.js';
5
+ import { validateResult } from '../contract/validate.js';
6
+ import { finalizeHandoff } from './handoff.js';
5
7
  export class StoreError extends Error {
6
8
  }
7
9
  const ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
@@ -21,6 +23,8 @@ function validExecutor(value) {
21
23
  const r = value;
22
24
  return !!r && r.format === 2 && r.kind === 'executor' && typeof r.executorId === 'string' && ID.test(r.executorId)
23
25
  && typeof r.parent?.session === 'string' && typeof r.harness === 'string' && typeof r.state === 'string'
26
+ && (r.model === undefined || typeof r.model === 'string')
27
+ && (r.reasoningEffort === undefined || typeof r.reasoningEffort === 'string')
24
28
  && typeof r.createdAt === 'string' && !!r.carrier && r.carrier.detached === true && Array.isArray(r.carrier.command);
25
29
  }
26
30
  /**
@@ -107,12 +111,19 @@ export class Ai4aiStore {
107
111
  }
108
112
  /**
109
113
  * Complete a pending operation in place. Durable operations are normally
110
- * append-only; a detached native watcher (Codex TUI /new) is the one case
111
- * where the same operation advances after its first result, so the pending
112
- * record is replaced with the terminal one. Terminal records are never
114
+ * append-only; a detached native watcher is the one case where the same
115
+ * operation advances after its first result, so the pending record is
116
+ * replaced with the terminal one. The replacement is contract-checked
117
+ * (including the same-session proof rule) and terminal records are never
113
118
  * rewritten.
114
119
  */
115
120
  async completePending(identity, operationId, outcome) {
121
+ const checked = validateResult(outcome);
122
+ if (!checked.ok)
123
+ throw new StoreError(`Pending completion violates the contract: ${checked.issues.map(i => `${i.path}:${i.code}`).join(', ')}`);
124
+ const finalized = finalizeHandoff({ ...(outcome.proof ? { proof: outcome.proof } : {}) });
125
+ if (finalized.error)
126
+ throw new StoreError(`Pending completion violates the handoff rule: ${finalized.error}`);
116
127
  return this.lock(async () => {
117
128
  const file = this.operationFile(identity);
118
129
  await contained(this.root, file);
@@ -125,6 +136,9 @@ export class Ai4aiStore {
125
136
  const existing = before.records[index];
126
137
  if (!['accepted', 'pending', 'applied'].includes(existing.status))
127
138
  return false;
139
+ if (outcome.operationId !== operationId || outcome.operation !== existing.request.operation) {
140
+ throw new StoreError('Pending completion belongs to a different operation; record left pending');
141
+ }
128
142
  const records = before.records.slice();
129
143
  records[index] = { ...existing, status: outcome.status, reason: outcome.reason, result: outcome };
130
144
  const raw = await bytes(file);
@@ -20,8 +20,7 @@
20
20
  "spawn-isolation",
21
21
  "spawn-policy",
22
22
  "model-override",
23
- "reasoning-effort-override",
24
- "tmux-fallback"
23
+ "reasoning-effort-override"
25
24
  ]
26
25
  },
27
26
  "description": "Feature names this caller requires; the request fails when the harness does not declare them."
@@ -1,6 +1,6 @@
1
1
  import type { AdapterContext, CarrierCommand, StatusDetails } from '../external.js';
2
2
  import { ExternalExecutorAdapter } from '../external.js';
3
- import type { CapabilityDeclaration } from '../../contract/types.js';
3
+ import type { CapabilityDeclaration, Request } from '../../contract/types.js';
4
4
  import type { HarnessId, Os } from '../../contract/states.js';
5
5
  import type { ExecutorRecord } from '../../core/store.js';
6
6
  import type { LogLine, ExecutorStatus } from '../executors.js';
@@ -15,6 +15,15 @@ export declare function claudePluginDir(home: string): string | undefined;
15
15
  export declare class ClaudeAdapter extends ExternalExecutorAdapter {
16
16
  readonly harness: HarnessId;
17
17
  capabilities(os: Os): CapabilityDeclaration[];
18
+ /**
19
+ * Persist the model a resumed turn must keep. The carrier passes `--model`
20
+ * only when the request has one, so the effective value can come from the
21
+ * settings `env` block (which overrides the inherited process environment)
22
+ * or the process environment.
23
+ */
24
+ protected persistedModel(request: Request, ctx: AdapterContext): Promise<string | undefined>;
25
+ /** `CLAUDE_CODE_EFFORT_LEVEL` overrides the settings `effortLevel`. */
26
+ protected persistedReasoningEffort(request: Request, ctx: AdapterContext): Promise<string | undefined>;
18
27
  protected carrier(request: Parameters<ExternalExecutorAdapter['spawn']>[0], ctx: AdapterContext, _executorId: string, resumeSessionId?: string): Promise<CarrierCommand>;
19
28
  protected statusDetails(_record: ExecutorRecord, status: ExecutorStatus, log: LogLine[], ctx: AdapterContext): Promise<StatusDetails>;
20
29
  }