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
@@ -4,6 +4,7 @@ import { randomUUID } from 'node:crypto';
4
4
  import { ExternalExecutorAdapter, lastJson } from '../external.js';
5
5
  import { resolveClaudeStatus } from './status.js';
6
6
  import { verifiedText, verifiedTokens, verifiedWindow } from '../../core/ladder.js';
7
+ import { envValue, probeClaudeSettings } from '../../core/config-probe.js';
7
8
  import { declaration } from '../declarations.js';
8
9
  /**
9
10
  * Claude Code adapter.
@@ -31,24 +32,48 @@ export function claudePluginDir(home) {
31
32
  export class ClaudeAdapter extends ExternalExecutorAdapter {
32
33
  harness = 'claude-code';
33
34
  capabilities(os) {
34
- const verified = os === 'linux' || os === 'darwin';
35
- const reason = os === 'linux'
36
- ? 'The mods plugin loads and both native handoff modes completed in place: restart via the built-in /clear (new session, same process) and compact via the native safe point; detached carriers spawn, report status and survive the parent. Exercised on Linux.'
37
- : os === 'darwin'
38
- ? 'The mods plugin loads and the native in-place handoff completed on macOS; detached carriers spawn and report status with model and context. Exercised on macOS.'
35
+ const linux = os === 'linux';
36
+ const mac = os === 'darwin';
37
+ // macOS proves both the handoff and the detached carrier in this release.
38
+ const reason = linux
39
+ ? 'The mods plugin loads and the zero-summary restart replaces the context in place through the native compact hook while keeping the session id; a disabled-compaction session is reported unsupported. Detached carriers spawn, report status and survive the parent. Exercised on Linux.'
40
+ : mac
41
+ ? 'The mods plugin loads and the zero-summary in-place restart completed on macOS with the session id preserved (handoff verified). The detached carrier was exercised on macOS with a real two-turn executor: spawn, status, message queued into the same session (both turn markers in the executor log), stop, and the error paths (unauthorized target, message to a completed executor) all completed.'
39
42
  : 'The mods plugin and the detached carrier are implemented; native Windows is out of scope (WSL counts as Linux) and was not exercised.';
40
- const level = verified ? 'supported' : 'not-tested';
43
+ const carrier = linux || mac ? 'supported' : 'not-tested';
41
44
  const common = {
42
- handoff: { availability: level, modes: ['compact', 'restart'], tmuxFallback: 'off' },
43
- spawn: { availability: level, maxConcurrent: 4 },
44
- status: { availability: level, model: level, reasoningEffort: 'unsupported', context: level, percentSource: 'derived' },
45
- ...(verified ? { evidence: `matrix:claude-code/${os}/2026-11-18` } : {}),
45
+ handoff: { availability: linux || mac ? 'supported' : 'not-tested', modes: ['restart'] },
46
+ spawn: { availability: carrier, maxConcurrent: 4 },
47
+ status: { availability: carrier, model: carrier, reasoningEffort: 'unsupported', context: carrier, percentSource: 'derived' },
48
+ ...(linux || mac ? { evidence: `matrix:claude-code/${os}/2026-11-21` } : {}),
46
49
  };
47
50
  return [
48
51
  declaration({ harness: 'claude-code', os, interface: 'tui', reason, ...common }),
49
52
  declaration({ harness: 'claude-code', os, interface: 'headless', reason, ...common }),
50
53
  ];
51
54
  }
55
+ /**
56
+ * Persist the model a resumed turn must keep. The carrier passes `--model`
57
+ * only when the request has one, so the effective value can come from the
58
+ * settings `env` block (which overrides the inherited process environment)
59
+ * or the process environment.
60
+ */
61
+ async persistedModel(request, ctx) {
62
+ if (request.model)
63
+ return request.model;
64
+ const settings = await probeClaudeSettings(ctx.identity.workspace, undefined, ['ANTHROPIC_MODEL']).catch(() => null);
65
+ return settings?.env[0]?.value ?? envValue('ANTHROPIC_MODEL') ?? undefined;
66
+ }
67
+ /** `CLAUDE_CODE_EFFORT_LEVEL` overrides the settings `effortLevel`. */
68
+ async persistedReasoningEffort(request, ctx) {
69
+ if (request.reasoningEffort)
70
+ return request.reasoningEffort;
71
+ const env = envValue('CLAUDE_CODE_EFFORT_LEVEL');
72
+ if (env)
73
+ return env;
74
+ const settings = await probeClaudeSettings(ctx.identity.workspace, undefined, []).catch(() => null);
75
+ return settings?.effortLevel?.value ?? undefined;
76
+ }
52
77
  async carrier(request, ctx, _executorId, resumeSessionId) {
53
78
  // A detached executor has no one to answer permission prompts: run it in the
54
79
  // harness's non-interactive bypass mode, consistent with the spawn contract.
@@ -1,4 +1,5 @@
1
1
  import type { Identity, Request, Result } from '../../contract/types.js';
2
+ import type { StoredProofMechanism } from '../../contract/states.js';
2
3
  export type ClaudePhase = 'pending' | 'scheduled' | 'applied' | 'completed' | 'cancelled' | 'failed' | 'unknown';
3
4
  export interface ClaudeRecord {
4
5
  format: 2;
@@ -11,6 +12,12 @@ export interface ClaudeRecord {
11
12
  reason: string;
12
13
  /** Native context replacement strategy recorded for this handoff. */
13
14
  mechanism?: 'restart' | 'compact';
15
+ /**
16
+ * Explicit proof mechanism. New records always set it. Records written
17
+ * before 0.0.5 lack it; their proof is derived from `mechanism` under the
18
+ * historical rules and is exempt from the same-session gate.
19
+ */
20
+ proofMechanism?: StoredProofMechanism;
14
21
  successor?: Identity;
15
22
  }
16
23
  export interface ClaudeCommand {
@@ -25,6 +32,7 @@ export interface ClaudeCommand {
25
32
  /** Native successor identity after a restart (new session id) or compact generation. */
26
33
  successor?: Identity;
27
34
  mechanism?: 'restart' | 'compact';
35
+ proofMechanism?: StoredProofMechanism;
28
36
  usage?: {
29
37
  window?: number | null;
30
38
  used?: number | null;
@@ -3,6 +3,7 @@ import path from 'node:path';
3
3
  import { atomicJson, bytes, contained, digest, ownership, withScopeLock } from '../../install/scope.js';
4
4
  import { result } from '../../contract/validate.js';
5
5
  import { handoffOutcome } from '../../contract/states.js';
6
+ import { legacyProofMechanism } from '../../core/handoff.js';
6
7
  const PHASES = ['pending', 'scheduled', 'applied', 'completed', 'cancelled', 'failed', 'unknown'];
7
8
  const sessionKey = (identity) => `${identity.workspace}\0${identity.surface}\0${identity.session}`;
8
9
  function response(record, operation = 'handoff') {
@@ -16,7 +17,9 @@ function response(record, operation = 'handoff') {
16
17
  ? {
17
18
  proof: {
18
19
  source: record.source, successor: record.successor,
19
- mechanism: (record.mechanism === 'restart' ? 'new-session' : 'surface-replacement'),
20
+ // New records carry the explicit field; old records keep the
21
+ // mechanism they historically implied and stay legacy-exempt.
22
+ mechanism: record.proofMechanism ?? legacyProofMechanism(record.mechanism),
20
23
  nativeEvidence: record.marker,
21
24
  },
22
25
  }
@@ -1,10 +1,91 @@
1
1
  import { TOOL_DESCRIPTION, TOOL_NAME, normalizeToolRequest } from '../../contract/tool.js';
2
- import { resolveBindingFile } from '../../install/binding.js';
3
2
  const tool = 'mcp__ai4ai__session';
4
3
  const dbg = ($, message) => { try {
5
4
  $.ui.log('ai4ai debug: ' + message, { to: 'debug' });
6
5
  }
7
6
  catch { /* debug only */ } };
7
+ // Import-free path helpers for the hooks sandbox (see the import comment).
8
+ const trimTrailing = (value) => value.replace(/[\\/]+$/, '');
9
+ const absolutePath = (value) => typeof value === 'string'
10
+ && (value.startsWith('/') || /^[A-Za-z]:[\\/]/.test(value) || value.startsWith('\\\\'));
11
+ const normalizedPath = (value) => {
12
+ const trimmed = trimTrailing(value).replace(/\\/g, '/');
13
+ // Windows paths compare case-insensitively; POSIX paths do not.
14
+ return /^[A-Za-z]:/.test(trimmed) || trimmed.startsWith('//') ? trimmed.toLowerCase() : trimmed;
15
+ };
16
+ const containsWorkspace = (root, candidate) => {
17
+ const owner = normalizedPath(root);
18
+ const target = normalizedPath(candidate);
19
+ return target === owner || target.startsWith(owner.endsWith('/') ? owner : `${owner}/`);
20
+ };
21
+ const parentPath = (value) => {
22
+ const trimmed = trimTrailing(value);
23
+ const index = Math.max(trimmed.lastIndexOf('/'), trimmed.lastIndexOf('\\'));
24
+ if (index < 0)
25
+ return trimmed;
26
+ if (index === 0)
27
+ return '/';
28
+ if (index === 2 && /^[A-Za-z]:/.test(trimmed))
29
+ return trimmed.slice(0, 3);
30
+ return trimmed.slice(0, index);
31
+ };
32
+ const joinPath = (directory, name) => {
33
+ const trimmed = trimTrailing(directory);
34
+ const separator = trimmed.includes('\\') && !trimmed.includes('/') ? '\\' : '/';
35
+ return `${trimmed}${separator}${name}`;
36
+ };
37
+ /** Read one binding candidate through the host API; malformed/foreign records are skipped. */
38
+ async function readBinding($, file) {
39
+ let raw;
40
+ try {
41
+ raw = await $.fs.read(file);
42
+ }
43
+ catch {
44
+ return undefined;
45
+ }
46
+ if (typeof raw !== 'string')
47
+ return undefined;
48
+ let value;
49
+ try {
50
+ value = JSON.parse(raw);
51
+ }
52
+ catch {
53
+ return undefined;
54
+ }
55
+ if (!value || value.product !== 'ai4ai' || value.format !== 2 || !absolutePath(value.home) || !absolutePath(value.workspace)
56
+ || typeof value.ownerToken !== 'string' || value.ownerToken.length === 0)
57
+ return undefined;
58
+ return {
59
+ home: value.home, workspace: value.workspace, ownerToken: value.ownerToken,
60
+ ...(typeof value.node === 'string' && absolutePath(value.node) ? { node: value.node } : {}),
61
+ };
62
+ }
63
+ /**
64
+ * Import-free binding resolution: the nearest workspace-local binding whose
65
+ * recorded workspace contains the caller wins; the plugin-root binding is a
66
+ * compatible fallback. The worker validates ownership again when used.
67
+ */
68
+ async function resolveBinding($) {
69
+ const workspace = await $.session.cwd();
70
+ if (typeof workspace !== 'string' || !absolutePath(workspace))
71
+ return undefined;
72
+ const candidates = [];
73
+ let current = workspace;
74
+ for (let depth = 0; depth < 16; depth += 1) {
75
+ candidates.push(joinPath(current, '.ai4ai/binding.json'));
76
+ const parent = parentPath(current);
77
+ if (parent === current)
78
+ break;
79
+ current = parent;
80
+ }
81
+ candidates.push(joinPath($.plugin.root, 'binding.json'));
82
+ for (const file of candidates) {
83
+ const binding = await readBinding($, file);
84
+ if (binding && containsWorkspace(binding.workspace, workspace))
85
+ return { binding, path: file };
86
+ }
87
+ return undefined;
88
+ }
8
89
  const projection = (rows) => JSON.stringify(rows.map((message) => ({
9
90
  role: message.role, text: message.text, toolUses: message.toolUses, toolResults: message.toolResults ?? [],
10
91
  })));
@@ -42,9 +123,9 @@ async function currentSurface($) {
42
123
  async function transition($, current, phase, reason, extra = {}, caller) {
43
124
  if (!current.binding || !current.active)
44
125
  return undefined;
45
- // The journal is keyed by the record's source session. After a restart the
46
- // in-memory binding points at the successor, so transitions must use the
47
- // source identity or the record would not be found.
126
+ // The journal is keyed by the record's source session. The in-place
127
+ // replacement keeps that session, but transitions still use the record's
128
+ // source identity so a later generation cannot be mistaken for it.
48
129
  const from = caller ?? current.active.source ?? current.binding;
49
130
  const out = await rpc($, current.node, {
50
131
  caller: from, action: 'transition', operationId: current.active.operationId,
@@ -93,62 +174,49 @@ async function pump($, s) {
93
174
  if (s.active?.phase !== 'scheduled')
94
175
  return;
95
176
  const mode = s.active.mechanism ?? s.active.request.mode ?? 'restart';
96
- if (mode === 'restart') {
97
- // Native in-place reset: the built-in /clear starts a new session with
98
- // empty context in the same process (the host pipe stays intact).
99
- const before = await $.session.id();
100
- const source = s.binding;
101
- if (!source)
102
- return;
103
- s.restarting = true;
104
- try {
105
- await $.command.run({ command: 'clear' });
106
- let after = before;
107
- for (let i = 0; i < 80 && after === before; i++) {
108
- await new Promise(resolve => setTimeout(resolve, 100));
109
- after = await $.session.id();
110
- }
111
- if (after === before) {
112
- await transition($, s, 'unknown', 'Native /clear did not produce a new session id; no task redelivery');
113
- return;
114
- }
115
- let display = '';
116
- try {
117
- display = JSON.stringify(await $.session.messages());
118
- }
119
- catch {
120
- display = '';
121
- }
122
- const clearSeen = display.includes('/clear') || display.includes('local_command');
123
- if (!clearSeen)
124
- dbg($, 'restart: /clear entry was not exposed by the plugin transcript view; the session id change is the native evidence');
125
- const successor = { ...source, session: after, generation: s.active.marker };
126
- await transition($, s, 'applied', clearSeen
127
- ? 'Native /clear reset the context in place; successor delivery pending'
128
- : 'Native /clear changed the session id in place; successor delivery pending', { successor, mechanism: 'restart' }, source);
129
- s.binding = successor;
130
- s.appliedHere = true;
131
- }
132
- finally {
133
- s.restarting = false;
134
- }
177
+ if (mode !== 'restart') {
178
+ // The native pump implements the zero-summary restart only. A compact
179
+ // request must be refused by the worker before it reaches this point.
180
+ await transition($, s, 'unknown', 'The native pump implements restart only; no replacement attempted');
181
+ return;
135
182
  }
136
- else {
137
- await $.command.run({ command: 'compact', args: s.active.marker });
138
- let api = '';
139
- try {
140
- api = JSON.stringify(await $.session.messages({ as: 'api' }));
141
- }
142
- catch {
143
- api = '';
144
- }
145
- if (!s.appliedHere || s.active.phase !== 'applied' || (api !== '' && !api.includes(s.active.marker))) {
146
- await transition($, s, 'unknown', 'Native replacement could not be proved; no task redelivery');
147
- return;
148
- }
149
- if (s.binding)
150
- s.binding = { ...s.binding, generation: s.active.marker };
183
+ const before = await $.session.id();
184
+ const source = s.binding;
185
+ if (!source)
186
+ return;
187
+ s.appliedHere = false;
188
+ s.replacement = undefined;
189
+ // `compact` runs the session.compact hook, which supplies a replacement
190
+ // message window and prevents the core compaction (and its summarizer)
191
+ // from running. The hook must finish inside the host's 10s budget, so it
192
+ // returns the window immediately and journals the transition separately.
193
+ await $.command.run({ command: 'compact', args: s.active.marker });
194
+ if (s.replacement)
195
+ await s.replacement;
196
+ // Explicit same-SID assertion: the replacement must not change the native
197
+ // session. A changed id is a defect, never a successful handoff.
198
+ const after = await $.session.id();
199
+ if (after !== before) {
200
+ await transition($, s, 'unknown', 'The native replacement changed the session id; the handoff was refused and the task was not delivered');
201
+ return;
202
+ }
203
+ if (!s.appliedHere || s.active?.phase !== 'applied') {
204
+ await transition($, s, 'unknown', 'Native replacement could not be proved; no task redelivery');
205
+ return;
206
+ }
207
+ let api = '';
208
+ try {
209
+ api = JSON.stringify(await $.session.messages({ as: 'api' }));
210
+ }
211
+ catch {
212
+ api = '';
213
+ }
214
+ if (api !== '' && !api.includes(s.active.marker)) {
215
+ await transition($, s, 'unknown', 'The replacement window does not contain the AI4AI binding; no task redelivery');
216
+ return;
151
217
  }
218
+ if (s.binding)
219
+ s.binding = { ...s.binding, generation: s.active.marker };
152
220
  const delivery = {
153
221
  text: `AI4AI handoff delivery ${s.active.marker}. Adopt the caller-supplied task in this fresh context. Carry out this task now:\n${s.active.request.task ?? ''}\nNative system/security instructions remain authoritative. Query ai4ai status if you need context or model details.`,
154
222
  operationId: s.active.operationId, marker: s.active.marker, invalid: false, adopted: false,
@@ -158,8 +226,11 @@ async function pump($, s) {
158
226
  }
159
227
  catch (error) {
160
228
  dbg($, 'pump failed: ' + String(error?.message ?? error));
229
+ const disabled = /DISABLE_COMPACT/i.test(String(error?.message ?? error));
161
230
  try {
162
- await transition($, s, 'unknown', 'Native scheduling outcome unknown; no replay');
231
+ await transition($, s, 'failed', disabled
232
+ ? 'Compaction is switched off in this session (DISABLE_COMPACT); the in-place restart is unsupported'
233
+ : 'Native scheduling outcome unknown; no replay');
163
234
  }
164
235
  catch { /* intent remains unreplayed */ }
165
236
  }
@@ -169,23 +240,14 @@ async function pump($, s) {
169
240
  }
170
241
  /** Native Claude Code mods: in-place handoff without a summarizer, daemon or history fork. */
171
242
  export const register = on => {
172
- const s = { instance: '', node: '', busy: false, pumping: false, restarting: false, turnId: '', expectedWindow: '', appliedHere: false };
243
+ const s = { instance: '', node: '', busy: false, pumping: false, turnId: '', expectedWindow: '', appliedHere: false };
173
244
  let tail = Promise.resolve();
174
245
  const serial = (fn) => { const pending = tail.then(fn); tail = pending.catch(() => undefined); return pending; };
175
246
  on('session.start', async ($, e, next) => {
176
247
  // A plugin cache can be shared by several workspaces. The workspace-local
177
248
  // binding always wins; the plugin-root copy is only a compatible fallback.
178
249
  try {
179
- const resolved = await resolveBindingFile({
180
- workspace: await $.session.cwd(),
181
- pluginRoot: $.plugin.root,
182
- read: async (file) => { try {
183
- return await $.fs.read(file);
184
- }
185
- catch {
186
- return undefined;
187
- } },
188
- });
250
+ const resolved = await resolveBinding($);
189
251
  if (resolved) {
190
252
  s.bindingPath = resolved.path;
191
253
  s.node = resolved.binding.node || process.execPath;
@@ -201,10 +263,9 @@ export const register = on => {
201
263
  inputSchema: JSON.parse(await $.fs.read(`${$.plugin.root}/request-schema.json`)),
202
264
  });
203
265
  try {
204
- // A native /clear restart re-enters session.start for the successor
205
- // session; bindNative would look up a journal that belongs to the source
206
- // session. Keep the in-memory restart binding instead.
207
- if (!s.restarting && (!s.binding || await $.session.id() !== s.binding.session))
266
+ // The in-place replacement keeps the same session, so an existing
267
+ // binding remains authoritative across a handoff.
268
+ if (!s.binding || await $.session.id() !== s.binding.session)
208
269
  await serial(() => bindNative($, s));
209
270
  }
210
271
  catch { /* Tool calls fail closed until a later successful bind. */ }
@@ -259,16 +320,47 @@ export const register = on => {
259
320
  await pump($, s);
260
321
  return out;
261
322
  });
323
+ // The host skips a hook that throws or exceeds its budget and then runs the
324
+ // core compaction, which would summarize the context and break the
325
+ // zero-token guarantee. This handler therefore never performs slow work: it
326
+ // validates in memory, returns the replacement window immediately and starts
327
+ // the journal write in the background. The mods loader requires the hook to
328
+ // be an inline function at the `on(...)` call site, so the fail-closed
329
+ // try/catch lives here rather than in an attached `.catch`.
262
330
  on('session.compact', async ($, e, next) => {
263
331
  if (e.agentId || !e.instructions?.startsWith('ai4ai-context-'))
264
332
  return next(e);
265
- return (async () => {
266
- if (!s.binding || !s.active || s.active.phase !== 'scheduled' || e.instructions !== s.active.marker || s.busy || (s.expectedWindow !== '' && projection(e.messages) !== s.expectedWindow)) {
267
- await transition($, s, 'unknown', 'Native compaction input changed or intent is not owned');
268
- return { skip: 'AI4AI did not authorize this replacement; original native context retained' };
333
+ try {
334
+ const refuse = (detail) => {
335
+ void transition($, s, 'unknown', `Native compaction input changed or intent is not owned: ${detail}`).catch(() => undefined);
336
+ return { skip: `AI4AI did not authorize this replacement; original native context retained (${detail})` };
337
+ };
338
+ if (!s.binding)
339
+ return refuse('no native binding');
340
+ if (!s.active)
341
+ return refuse('no active handoff record');
342
+ // Fault-injection seam used only by the release gate: a caller that
343
+ // deliberately uses this operation id exercises the fail-closed catch.
344
+ // It is inert for every other operation id.
345
+ if (s.active.operationId === 'ai4ai-hook-fault-throw')
346
+ throw new Error('injected session.compact hook fault');
347
+ if (s.active.phase !== 'scheduled')
348
+ return refuse(`handoff phase is ${String(s.active.phase)}`);
349
+ if (e.instructions !== s.active.marker)
350
+ return refuse('marker does not match the owned intent');
351
+ if (s.busy)
352
+ return refuse('the plugin is busy with another native turn');
353
+ let observed = '';
354
+ try {
355
+ observed = projection(e.messages ?? []);
269
356
  }
270
- await transition($, s, 'applied', 'Native compact hook supplied a fresh task window; successor adoption pending');
357
+ catch {
358
+ return refuse('the native window could not be read');
359
+ }
360
+ if (s.expectedWindow !== '' && observed !== s.expectedWindow)
361
+ return refuse('the native window changed since scheduling');
271
362
  s.appliedHere = true;
363
+ s.replacement = transition($, s, 'applied', 'Native compact hook supplied a fresh task window; successor adoption pending');
272
364
  return {
273
365
  messages: [{
274
366
  role: 'user',
@@ -276,27 +368,42 @@ export const register = on => {
276
368
  toolUses: [],
277
369
  }],
278
370
  };
279
- })().catch(() => ({ skip: 'AI4AI native gate failed closed; no replacement authorized' }));
371
+ }
372
+ catch (error) {
373
+ s.appliedHere = false;
374
+ const detail = String(error?.message ?? error).slice(0, 300);
375
+ dbg($, 'session.compact gate failed closed: ' + detail);
376
+ return { skip: 'AI4AI native gate failed closed; no replacement authorized (' + detail + ')' };
377
+ }
280
378
  });
281
379
  on('prompt.submit', async ($, e, next) => {
282
380
  const own = e.origin.kind === 'plugin' && e.origin.name === $.plugin.name;
381
+ const isDelivery = own && String(e.text ?? '').startsWith('AI4AI handoff delivery ');
283
382
  const ownCompact = e.command?.name === 'compact' && e.command.args === s.active?.marker && s.pumping;
284
- if (own && e.text.startsWith('AI4AI handoff delivery ')) {
285
- const allow = await serial(async () => e.text === s.delivery?.text && admitted(s) && await $.session.id() === s.binding?.session);
286
- if (!allow)
287
- return { drop: 'Superseded or uncertain AI4AI delivery; task not admitted' };
383
+ try {
384
+ if (isDelivery) {
385
+ // Delivery admission must prove the replacement actually happened in
386
+ // this session; anything uncertain drops the task instead of injecting
387
+ // it into a stale context.
388
+ const allow = await serial(async () => e.text === s.delivery?.text && admitted(s) && await $.session.id() === s.binding?.session);
389
+ if (!allow)
390
+ return { drop: 'Superseded or uncertain AI4AI delivery; task not admitted' };
391
+ }
392
+ else if (!ownCompact && !s.pumping)
393
+ await serial(async () => { if (s.active && s.active.phase === 'pending')
394
+ await transition($, s, 'cancelled', 'Later user input retained; handoff not replayed'); });
395
+ }
396
+ catch {
397
+ // Never fail open on the one path that injects handoff material.
398
+ if (isDelivery)
399
+ return { drop: 'AI4AI delivery admission failed closed; task not admitted' };
288
400
  }
289
- else if (!ownCompact && !s.restarting && !s.pumping)
290
- await serial(async () => { if (s.active && s.active.phase === 'pending')
291
- await transition($, s, 'cancelled', 'Later user input retained; handoff not replayed'); });
292
401
  return next(e);
293
402
  });
294
403
  on('session.end', async ($, e, next) => {
295
- // The /clear restart ends the source session on purpose; the successor
296
- // session owns the handoff now, so the source must not mark it unknown.
404
+ // The in-place replacement keeps this session; an unfinished handoff at
405
+ // session end is genuinely uncertain and never replayed.
297
406
  await serial(async () => {
298
- if (s.restarting || (s.active?.mechanism === 'restart' && s.delivery))
299
- return;
300
407
  if (s.active && !['completed', 'cancelled', 'failed', 'unknown'].includes(s.active.phase))
301
408
  await transition($, s, 'unknown', 'Native session ended; unfinished handoff is not resumed automatically');
302
409
  });
@@ -12,7 +12,7 @@ import { handoffMode, handoffOutcome } from '../../contract/states.js';
12
12
  import { fingerprint } from '../../core/fingerprint.js';
13
13
  import { activeRecord } from '../../core/journal.js';
14
14
  import { Ai4aiStore } from '../../core/store.js';
15
- import { execute } from '../../core/operations.js';
15
+ import { currentOs, execute } from '../../core/operations.js';
16
16
  import { ClaudeJournal, response } from './journal.js';
17
17
  import { ClaudeAdapter } from './adapter.js';
18
18
  import { resolveClaudeStatus } from './status.js';
@@ -99,12 +99,19 @@ if (command.action === 'transition') {
99
99
  const to = command.phase ?? 'unknown';
100
100
  if (!allowed[to]?.includes(latest.phase))
101
101
  throw new Error(`Unexpected transition ${latest.phase} -> ${to}; no replay`);
102
+ const successor = command.successor ?? { ...latest.source, generation: latest.marker };
103
+ // A handoff never changes the native session identity; the plugin asserts
104
+ // this too, and the journal refuses a mismatched record rather than storing
105
+ // a false success.
106
+ if (successor.session !== latest.source.session)
107
+ throw new Error('Handoff successor changed the native session id; no transition recorded');
102
108
  const next = {
103
109
  ...latest, phase: to, reason: command.reason ?? to,
104
110
  ...(to === 'applied'
105
111
  ? {
106
- successor: command.successor ?? { ...latest.source, generation: latest.marker },
107
- mechanism: command.mechanism ?? latest.mechanism ?? 'compact',
112
+ successor,
113
+ mechanism: command.mechanism ?? latest.mechanism ?? 'restart',
114
+ proofMechanism: command.proofMechanism ?? latest.proofMechanism ?? 'surface-replacement',
108
115
  }
109
116
  : {}),
110
117
  };
@@ -131,9 +138,12 @@ if (request.operation === 'status' && (request.target === undefined || request.t
131
138
  });
132
139
  const pointer = await sessionPointer('claude-code', caller.workspace, caller.session).catch(() => null);
133
140
  const activity = await sessionActivity(pointer?.path ?? null);
141
+ const compactionDisabled = !!process.env.DISABLE_COMPACT && process.env.DISABLE_COMPACT !== '0';
134
142
  console.log(JSON.stringify({
135
143
  result: result(request, 'completed', 'Native session status', {
136
144
  durable: true,
145
+ // A session-level limit, reported honestly without blocking status.
146
+ ...(compactionDisabled ? { notices: [{ code: 'claude-compaction-disabled', impact: 'none', action_required: false, message: 'Compaction is switched off in this session (DISABLE_COMPACT); the in-place restart handoff is unsupported here.' }] } : {}),
137
147
  // The session is alive while it serves this call; handoff progress is
138
148
  // reported separately, and quiescence is inferred from lastActivityAt.
139
149
  state: 'running',
@@ -155,7 +165,7 @@ if (request.operation === 'status' && (request.target === undefined || request.t
155
165
  process.exit(0);
156
166
  }
157
167
  if (request.operation === 'capabilities') {
158
- console.log(JSON.stringify({ result: result(request, 'completed', 'Claude adapter capabilities are declared by the installed plugin', { durable: false }) }));
168
+ console.log(JSON.stringify({ result: result(request, 'completed', 'Claude adapter capabilities are declared by the installed plugin', { durable: false, capabilities: new ClaudeAdapter().capabilities(currentOs()) }) }));
159
169
  process.exit(0);
160
170
  }
161
171
  if (request.operation === 'cancel' || request.operation === 'stop') {
@@ -183,8 +193,21 @@ if (request.operation === 'handoff' && request.target === 'self') {
183
193
  console.log(JSON.stringify({ result: result(request, 'failed', 'Another handoff is unresolved; reconcile it before requesting a transition') }));
184
194
  process.exit(0);
185
195
  }
196
+ // Compaction can be switched off per session; the restart path needs it, so
197
+ // report the limitation up front instead of failing midway.
198
+ if (process.env.DISABLE_COMPACT && process.env.DISABLE_COMPACT !== '0') {
199
+ console.log(JSON.stringify({ result: result(request, 'unsupported', 'Compaction is switched off in this session (DISABLE_COMPACT); the in-place restart handoff needs it', { unavailable: ['handoff.restart'], error: { code: 'claude-compaction-disabled', message: 'DISABLE_COMPACT is set for this session' } }) }));
200
+ process.exit(0);
201
+ }
202
+ // This version declares restart only. `compact` means a native summary,
203
+ // which Claude does not implement here; refuse it instead of silently
204
+ // running the zero-summary replacement under a compact label.
205
+ if (request.mode === 'compact') {
206
+ console.log(JSON.stringify({ result: result(request, 'unsupported', 'Claude Code handoff implements restart only in this version; native compaction plus task delivery is not available', { unavailable: ['handoff.compact'] }) }));
207
+ process.exit(0);
208
+ }
186
209
  const mechanism = handoffMode(request.mode);
187
- if (mechanism === 'restart' && !request.task) {
210
+ if (!request.task) {
188
211
  console.log(JSON.stringify({ result: result(request, 'unsupported', 'A restart handoff needs task material: the new context contains only that material', { unavailable: ['handoff.task'] }) }));
189
212
  process.exit(0);
190
213
  }
@@ -192,9 +215,8 @@ if (request.operation === 'handoff' && request.target === 'self') {
192
215
  const record = {
193
216
  format: 2, operationId: request.operationId, fingerprint: fingerprint(request), request, source: caller, marker, phase: 'pending',
194
217
  mechanism,
195
- reason: mechanism === 'restart'
196
- ? 'Finish this turn; the native /clear reset replaces this context with the caller task material'
197
- : 'Finish this turn; the native safe point will replace the context with the caller task material',
218
+ proofMechanism: 'surface-replacement',
219
+ reason: 'Finish this turn; the native compact hook replaces this context in place with the caller task material (no summary model is called)',
198
220
  };
199
221
  await journal.transaction(caller, async (_rows, commit) => commit(record));
200
222
  console.log(JSON.stringify({ result: response(record), record }));