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
@@ -1,11 +1,48 @@
1
- import type { AdapterContext, CarrierCommand, StatusDetails } from '../external.js';
1
+ import type { AdapterContext, CarrierCommand, StatusDetails, NativeOutcome } 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';
7
+ /**
8
+ * DeepSeek Harness adapter.
9
+ *
10
+ * The in-harness Cordis plugin implements same-session handoff; the external
11
+ * adapter owns detached `dsh headless` processes. The web surface is verified
12
+ * separately through an isolated DSH_HOME instance.
13
+ */
14
+ /** Windows looks up executable extensions from PATHEXT; this is the documented fallback. */
15
+ export declare const DEFAULT_PATHEXT: readonly [".EXE", ".CMD", ".BAT"];
16
+ export interface ExecutableResolverOptions {
17
+ platform: NodeJS.Platform | 'linux' | 'darwin' | 'win32';
18
+ env: NodeJS.ProcessEnv;
19
+ /** Injectable for unit tests; defaults to a real file check. */
20
+ exists?: (candidate: string) => boolean;
21
+ isFile?: (candidate: string) => boolean;
22
+ }
23
+ /**
24
+ * Resolve an executable name the way Windows does: a bare name (or a name with
25
+ * a non-executable extension) is tried against every PATHEXT suffix in each
26
+ * PATH directory, case-insensitively. A path containing `%` is refused because
27
+ * cmd.exe would expand it.
28
+ */
29
+ export declare function resolveExecutable(name: string, options: ExecutableResolverOptions): string | undefined;
30
+ /**
31
+ * Build the single `/c` payload cmd.exe receives under `/d /s /c`.
32
+ *
33
+ * `/s` strips exactly the outer pair of quotes, leaving
34
+ * `"C:\path with space\dsh.cmd" headless ...` for cmd's own parser. The whole
35
+ * argv element therefore starts with two quotes and ends with one.
36
+ */
37
+ export declare function windowsCommandLine(entry: string, args: readonly string[]): string;
7
38
  export declare class DshAdapter extends ExternalExecutorAdapter {
8
39
  readonly harness: HarnessId;
40
+ /**
41
+ * DSH headless accepts no model or reasoning-effort selector (verified with
42
+ * `dsh headless --help`). Refuse the override instead of building a command
43
+ * that is guaranteed to exit 1. Handoff behavior is unchanged.
44
+ */
45
+ spawn(request: Request, ctx: AdapterContext): Promise<NativeOutcome>;
9
46
  private command;
10
47
  capabilities(os: Os): CapabilityDeclaration[];
11
48
  protected carrier(request: Parameters<ExternalExecutorAdapter['spawn']>[0], ctx: AdapterContext, _executorId: string, resumeSessionId?: string): Promise<CarrierCommand>;
@@ -1,5 +1,5 @@
1
1
  import path from 'node:path';
2
- import { existsSync } from 'node:fs';
2
+ import { existsSync, statSync } from 'node:fs';
3
3
  import { ExternalExecutorAdapter, lastJson } from '../external.js';
4
4
  import { declaration } from '../declarations.js';
5
5
  import { verifiedTokens } from '../../core/ladder.js';
@@ -13,30 +13,113 @@ import { resolveDshStatus } from './status.js';
13
13
  * adapter owns detached `dsh headless` processes. The web surface is verified
14
14
  * separately through an isolated DSH_HOME instance.
15
15
  */
16
- /** First executable `dsh` on PATH (PATHEXT-aware on Windows). */
17
- function lookPath(name) {
18
- const search = process.env.PATH;
19
- if (!search)
16
+ /** Windows looks up executable extensions from PATHEXT; this is the documented fallback. */
17
+ export const DEFAULT_PATHEXT = ['.EXE', '.CMD', '.BAT'];
18
+ /** Session ids are placed on a command line; reject anything outside this alphabet. */
19
+ const SESSION_ID = /^[A-Za-z0-9._:-]+$/;
20
+ function windowsExtensions(env) {
21
+ const declared = env.PATHEXT?.split(';').map(value => value.trim()).filter(Boolean) ?? [];
22
+ const extensions = declared.length ? declared : [...DEFAULT_PATHEXT];
23
+ // A name already carrying a known extension is tested as-is first.
24
+ return extensions.map(value => value.startsWith('.') ? value : `.${value}`);
25
+ }
26
+ function hasKnownExtension(name, extensions) {
27
+ return extensions.some(extension => name.toLowerCase().endsWith(extension.toLowerCase()));
28
+ }
29
+ function pathDirectories(platform, env) {
30
+ const delimiter = platform === 'win32' ? ';' : ':';
31
+ return (env.PATH ?? '').split(delimiter).filter(Boolean);
32
+ }
33
+ /** Join with the target platform's separator, not the host's. */
34
+ function joinFor(platform, directory, name) {
35
+ return platform === 'win32'
36
+ ? `${directory.replace(/[\\/]+$/, '')}\\${name}`
37
+ : path.join(directory, name);
38
+ }
39
+ /**
40
+ * Resolve an executable name the way Windows does: a bare name (or a name with
41
+ * a non-executable extension) is tried against every PATHEXT suffix in each
42
+ * PATH directory, case-insensitively. A path containing `%` is refused because
43
+ * cmd.exe would expand it.
44
+ */
45
+ export function resolveExecutable(name, options) {
46
+ const exists = options.exists ?? existsSync;
47
+ const isFile = options.isFile ?? ((candidate) => { try {
48
+ return statSync(candidate).isFile();
49
+ }
50
+ catch {
51
+ return false;
52
+ } });
53
+ if (!name || name.includes('%'))
54
+ return undefined;
55
+ const windows = options.platform === 'win32';
56
+ const hasSeparator = name.includes('/') || name.includes('\\');
57
+ const extensions = windows ? windowsExtensions(options.env) : [];
58
+ const tryFile = (candidate) => candidate.includes('%') ? undefined : exists(candidate) && isFile(candidate) ? candidate : undefined;
59
+ const candidatesFor = (base) => {
60
+ if (!windows)
61
+ return [base];
62
+ const list = [];
63
+ if (hasKnownExtension(base, extensions))
64
+ list.push(base);
65
+ else
66
+ for (const extension of extensions)
67
+ list.push(base + extension);
68
+ return list;
69
+ };
70
+ if (path.isAbsolute(name) || hasSeparator) {
71
+ for (const candidate of candidatesFor(name)) {
72
+ const found = tryFile(candidate);
73
+ if (found)
74
+ return found;
75
+ }
20
76
  return undefined;
21
- // The carrier is spawned without a shell, so only real executables count on
22
- // Windows: a .cmd/.bat shim cannot be executed directly.
23
- const extensions = process.platform === 'win32' ? ['.exe'] : [''];
24
- for (const directory of search.split(path.delimiter)) {
25
- if (!directory)
26
- continue;
27
- for (const extension of extensions) {
28
- const candidate = path.join(directory, name + extension.toLowerCase());
29
- try {
30
- if (existsSync(candidate))
31
- return candidate;
32
- }
33
- catch { /* keep searching */ }
77
+ }
78
+ for (const directory of pathDirectories(String(options.platform), options.env)) {
79
+ for (const candidate of candidatesFor(joinFor(String(options.platform), directory, name))) {
80
+ const found = tryFile(candidate);
81
+ if (found)
82
+ return found;
34
83
  }
35
84
  }
36
85
  return undefined;
37
86
  }
87
+ /**
88
+ * Build the single `/c` payload cmd.exe receives under `/d /s /c`.
89
+ *
90
+ * `/s` strips exactly the outer pair of quotes, leaving
91
+ * `"C:\path with space\dsh.cmd" headless ...` for cmd's own parser. The whole
92
+ * argv element therefore starts with two quotes and ends with one.
93
+ */
94
+ export function windowsCommandLine(entry, args) {
95
+ return `""${entry}" ${args.join(' ')}"`;
96
+ }
97
+ /** First executable `dsh` on PATH (PATHEXT-aware on Windows). */
98
+ function lookPath(name) {
99
+ return resolveExecutable(name, { platform: process.platform, env: process.env });
100
+ }
38
101
  export class DshAdapter extends ExternalExecutorAdapter {
39
102
  harness = 'dsh';
103
+ /**
104
+ * DSH headless accepts no model or reasoning-effort selector (verified with
105
+ * `dsh headless --help`). Refuse the override instead of building a command
106
+ * that is guaranteed to exit 1. Handoff behavior is unchanged.
107
+ */
108
+ async spawn(request, ctx) {
109
+ const unavailable = [];
110
+ if (request.model !== undefined)
111
+ unavailable.push('spawn.model');
112
+ if (request.reasoningEffort !== undefined)
113
+ unavailable.push('spawn.reasoningEffort');
114
+ if (unavailable.length) {
115
+ return {
116
+ status: 'unsupported',
117
+ reason: `dsh headless does not accept model or reasoning-effort overrides (${unavailable.join(', ')}); configure the DSH profile instead and omit them`,
118
+ unavailable,
119
+ };
120
+ }
121
+ return super.spawn(request, ctx);
122
+ }
40
123
  command() {
41
124
  if (process.env.AI4AI_DSH_ENTRY) {
42
125
  return { command: process.env.AI4AI_DSH_NODE || process.execPath, prefix: [process.env.AI4AI_DSH_ENTRY] };
@@ -46,45 +129,89 @@ export class DshAdapter extends ExternalExecutorAdapter {
46
129
  // A bare `dsh` remains the last resort so the failure mode is unchanged
47
130
  // when none of these is present.
48
131
  const explicit = process.env.AI4AI_DSH_BIN || process.env.DSH_BIN;
132
+ if (process.platform === 'win32') {
133
+ const requested = explicit ?? 'dsh';
134
+ const resolved = resolveExecutable(requested, { platform: 'win32', env: process.env });
135
+ if (!resolved)
136
+ return { command: requested, prefix: [] };
137
+ return /\.(?:cmd|bat)$/i.test(resolved)
138
+ ? { command: process.env.ComSpec || process.env.COMSPEC || 'cmd.exe', prefix: [], entry: resolved }
139
+ : { command: resolved, prefix: [] };
140
+ }
49
141
  if (explicit)
50
142
  return { command: explicit, prefix: [] };
51
143
  const found = lookPath('dsh');
52
144
  return { command: found || 'dsh', prefix: [] };
53
145
  }
54
146
  capabilities(os) {
147
+ // All three platforms were exercised in this release. macOS and native
148
+ // Windows use the DSH_HOME credential chain (OPENCODE_API_KEY) rather than
149
+ // a clean profile without credentials. On Windows the installer needs the
150
+ // real JS entry (AI4AI_DSH_ENTRY) because a .cmd entry is refused, but the
151
+ // carrier also accepts a .cmd wrapper. The Web surface was exercised through
152
+ // the Web UI on all three platforms (isolated profiles, no live restart).
55
153
  const linux = os === 'linux';
56
154
  const mac = os === 'darwin';
57
155
  const windows = os === 'windows';
58
156
  const reason = linux
59
- ? 'Detached dsh headless carriers were exercised with a real session and usage reporting; the Cordis plugin implements same-session surface replacement and the handoff journal/apply/successor path is verified.'
157
+ ? 'Detached dsh headless carriers were exercised with a real session and usage reporting; the Cordis plugin implements same-session surface replacement and the handoff journal/apply/successor path is verified. The Web surface was exercised through the Web UI (capabilities/status/list/spawn/status-poll/stop and a same-session handoff). spawn model/effort overrides are unsupported.'
60
158
  : mac
61
- ? 'macOS headless carrier and the Cordis same-session handoff were verified with the installed DSH and its existing credential path; detached spawn/status use the same carrier.'
62
- : 'Native Windows headless spawn/status and the Cordis same-session handoff were verified with the installed DSH runtime and a new test profile.';
63
- const carrier = linux || mac || windows ? 'supported' : 'not-tested';
64
- const handoffLevel = linux || mac || windows ? 'supported' : 'not-tested';
65
- const common = {
66
- handoff: { availability: handoffLevel, modes: ['restart'], tmuxFallback: 'off' },
159
+ ? 'macOS headless handoff was exercised with a real provider from the DSH_HOME credential chain: the model invoked ai4ai_session itself, the successor turn ran in the same session with surface-replacement proof, and the detached carrier completed spawn/status/message×2/stop/error. The Web surface was exercised through the Web UI on an isolated profile (capabilities/status/list/spawn/message two turns in one session/stop/error). spawn model/effort overrides are unsupported.'
160
+ : 'Native Windows headless handoff, spawn/status/message×2/stop/error and the .cmd carrier were exercised with the DSH plugin-manager profile and the real JS entry (AI4AI_DSH_ENTRY); the installer refuses a .cmd entry but succeeds with the JS entry. The Web surface was exercised through the Web UI on an isolated profile (capabilities/status/list/spawn/message two turns in one session/stop/error). spawn model/effort overrides are unsupported.';
161
+ const carrier = 'supported';
162
+ const headlessHandoff = 'supported';
163
+ const webLevel = 'supported';
164
+ const headless = {
165
+ handoff: { availability: headlessHandoff, modes: ['restart'] },
67
166
  spawn: { availability: carrier, maxConcurrent: 4 },
68
167
  status: { availability: carrier, model: 'not-tested', reasoningEffort: 'not-tested', context: carrier, percentSource: 'derived' },
69
- ...(linux || mac ? { evidence: `matrix:dsh/${os}/headless/2026-11-18` } : {}),
168
+ evidence: `matrix:dsh/${os}/headless/2026-11-21`,
169
+ };
170
+ const web = {
171
+ handoff: { availability: webLevel, modes: ['restart'] },
172
+ spawn: { availability: webLevel, maxConcurrent: 4 },
173
+ status: { availability: webLevel, model: 'not-tested', reasoningEffort: 'not-tested', context: webLevel, percentSource: 'native' },
174
+ evidence: `matrix:dsh/${os}/web/2026-11-21`,
70
175
  };
176
+ const webReason = linux
177
+ ? 'The Linux Web surface was exercised through the Web UI: ai4ai_session capabilities/status/list/spawn/status-poll/stop completed, and a Web handoff completed in the same session with the old codeword absent from the replaced context. The live Web profile runs 0.0.5 and is healthy. spawn model/effort overrides are unsupported.'
178
+ : mac
179
+ ? 'The macOS Web surface was exercised through the Web UI on an isolated web profile: ai4ai_session capabilities/status/list/spawn/message/status-poll/stop completed, the message was accepted into the running executor and its second turn replied in the same session, and the unauthorized target returned a structured error. The live Web profile runs 0.0.5 and is healthy. spawn model/effort overrides are unsupported.'
180
+ : 'The native Windows Web surface was exercised through the Web UI on an isolated web profile: ai4ai_session capabilities/status/list/spawn/message/status-poll/stop completed, the message was queued into the running executor and its second turn replied in the same session, and the unauthorized target returned a structured error. The live Web profiles run 0.0.5 and are healthy. spawn model/effort overrides are unsupported.';
71
181
  return [
72
- declaration({ harness: 'dsh', os, interface: 'headless', reason, ...common }),
73
- declaration({ harness: 'dsh', os, interface: 'web', reason, ...common, status: { ...common.status, percentSource: 'native' } }),
182
+ declaration({ harness: 'dsh', os, interface: 'headless', reason, ...headless }),
183
+ declaration({ harness: 'dsh', os, interface: 'web', reason: webReason, ...web }),
74
184
  ];
75
185
  }
76
186
  async carrier(request, ctx, _executorId, resumeSessionId) {
77
- const { command, prefix } = this.command();
78
- const args = [...prefix, 'headless', '--json', '-'];
187
+ if (resumeSessionId !== undefined && !SESSION_ID.test(resumeSessionId)) {
188
+ // Never silently fall back to a session-less turn: that would lose the
189
+ // previous context the caller is continuing.
190
+ const error = new Error(`Refusing an unsafe DSH session id: ${JSON.stringify(resumeSessionId).slice(0, 120)}`);
191
+ error.code = 'message-session-unknown';
192
+ throw error;
193
+ }
194
+ const plan = this.command();
195
+ // DSH headless has no model/effort flags; the profile owns those choices.
196
+ const headless = ['headless', '--json', '-'];
79
197
  if (resumeSessionId)
80
- args.push('--session-id', resumeSessionId);
81
- if (request.model)
82
- args.push('--model', request.model);
198
+ headless.push('--session-id', resumeSessionId);
199
+ const env = { ...(process.env.DSH_HOME ? { DSH_HOME: process.env.DSH_HOME } : {}) };
200
+ const sessionRegex = '"session(?:Id|ID|_id)"\\s*:\\s*"([^"]+)"';
201
+ if (plan.entry) {
202
+ return {
203
+ command: plan.command,
204
+ args: ['/d', '/s', '/c', windowsCommandLine(plan.entry, [...plan.prefix, ...headless])],
205
+ env,
206
+ windowsVerbatimArguments: true,
207
+ sessionRegex,
208
+ };
209
+ }
83
210
  return {
84
- command,
85
- args,
86
- env: { ...(process.env.DSH_HOME ? { DSH_HOME: process.env.DSH_HOME } : {}) },
87
- sessionRegex: '"session(?:Id|ID|_id)"\\s*:\\s*"([^"]+)"',
211
+ command: plan.command,
212
+ args: [...plan.prefix, ...headless],
213
+ env,
214
+ sessionRegex,
88
215
  };
89
216
  }
90
217
  async statusDetails(record, status, log, ctx) {
@@ -93,9 +93,11 @@ interface JournalRecord {
93
93
  proof?: {
94
94
  source: Identity;
95
95
  successor: Identity;
96
- mechanism: 'new-session';
96
+ mechanism: 'new-session' | 'surface-replacement' | 'native-compaction';
97
97
  nativeEvidence: string;
98
98
  };
99
+ /** Explicit proof mechanism; absent on records written before 0.0.5. */
100
+ proofMechanism?: 'surface-replacement' | 'native-compaction';
99
101
  reason?: string;
100
102
  /** Exact request covered by the fingerprint; keeps later parsing independent of optional fields. */
101
103
  request?: {
@@ -4,11 +4,12 @@ import { handoffOutcome } from '../../contract/states.js';
4
4
  import { REQUEST_SCHEMA } from '../../contract/schema.js';
5
5
  import { fingerprint, sameIdentity } from '../../core/fingerprint.js';
6
6
  import { Ai4aiStore } from '../../core/store.js';
7
- import { execute } from '../../core/operations.js';
7
+ import { currentOs, execute } from '../../core/operations.js';
8
8
  import { DshAdapter } from './adapter.js';
9
9
  import { TOOL_DESCRIPTION, normalizeToolRequest } from '../../contract/tool.js';
10
10
  import { reconcileDshStatus, resolveDshStatus } from './status.js';
11
11
  import { sessionActivity, sessionPointer } from '../../core/session-probe.js';
12
+ import { effectiveDshSelection, foldDshSelection } from '../../core/dsh-selection.js';
12
13
  const TOOL = 'ai4ai_session';
13
14
  const SOURCE = 'ai4ai-coordination';
14
15
  const rootAgent = (agent) => typeof agent.session.header.cwd === 'string' && agent.session.header.cwd.length > 0
@@ -22,8 +23,14 @@ function identity(agent) {
22
23
  }
23
24
  function journal(events, session) {
24
25
  const records = [];
26
+ // After a surface replacement the applied record lives in the current
27
+ // window but may sit below `inheritedEventCount` (which describes history
28
+ // carried over from before the window). Surface nodes are the authoritative
29
+ // current window, so include them explicitly; otherwise a status/requery
30
+ // after a successful handoff would report "no handoff started".
31
+ const surfaceNodes = new Set(session.surface.nodes);
25
32
  for (const event of events) {
26
- if (event.seq < session.inheritedEventCount)
33
+ if (event.seq < session.inheritedEventCount && !surfaceNodes.has(event.seq))
27
34
  continue;
28
35
  if (event.type !== 'user/message' || event.data.source?.kind !== SOURCE)
29
36
  continue;
@@ -39,6 +46,8 @@ function journal(events, session) {
39
46
  const request = validateRequest(source);
40
47
  if (record.version !== 2 || !request.ok || !record.owner || record.owner.session !== session.id
41
48
  || record.fingerprint !== fingerprint(request.value) || !Number.isSafeInteger(record.boundary)
49
+ || (record.proofMechanism !== undefined && !['surface-replacement', 'native-compaction'].includes(record.proofMechanism))
50
+ || (record.proof !== undefined && !['new-session', 'surface-replacement', 'native-compaction'].includes(record.proof.mechanism))
42
51
  || !['intent', 'applied', 'cancelled', 'failed', 'blocked'].includes(record.phase)) {
43
52
  throw new Error('Native operation journal is incompatible; no transition authorized');
44
53
  }
@@ -133,8 +142,12 @@ export function apply(ctx) {
133
142
  exec.signal.throwIfAborted();
134
143
  const session = agent.session;
135
144
  const caller = identity(agent);
136
- if (request.operation === 'capabilities')
137
- return result(request, 'completed', 'DSH adapter capabilities are declared by the packaged adapter', { durable: false });
145
+ if (request.operation === 'capabilities') {
146
+ return result(request, 'completed', 'DSH adapter capabilities are declared by the packaged adapter', {
147
+ durable: false,
148
+ capabilities: new DshAdapter().capabilities(currentOs()),
149
+ });
150
+ }
138
151
  const events = await snapshot(session);
139
152
  const records = journal(events, session);
140
153
  const stored = latest(records, request.operationId);
@@ -144,27 +157,19 @@ export function apply(ctx) {
144
157
  }
145
158
  if (request.operation === 'status') {
146
159
  const native = {};
160
+ // Model and effort use the official projections fold, exactly like
161
+ // the external adapter's persisted-session path.
162
+ const selection = effectiveDshSelection(foldDshSelection(events.map(event => ({ type: event.type, data: event.data }))));
163
+ if (selection) {
164
+ native.model = selection.model;
165
+ native.reasoningEffort = selection.reasoningEffort;
166
+ }
147
167
  for (const event of events) {
148
168
  const data = event.data && typeof event.data === 'object' ? event.data : {};
149
169
  if (event.type === 'request/context') {
150
- if (typeof data.model === 'string')
151
- native.model = data.model;
152
170
  if (typeof data.contextWindow === 'number')
153
171
  native.window = data.contextWindow;
154
172
  }
155
- else if (event.type === 'request/header') {
156
- const config = data.header?.config && typeof data.header.config === 'object' ? data.header.config : {};
157
- if (typeof config.model === 'string')
158
- native.model = native.model ?? config.model;
159
- if (typeof config.reasoningEffort === 'string')
160
- native.reasoningEffort = config.reasoningEffort;
161
- }
162
- else if (event.type === 'model/selection') {
163
- if (typeof data.model === 'string')
164
- native.model = data.model;
165
- if (typeof data.reasoningEffort === 'string')
166
- native.reasoningEffort = data.reasoningEffort;
167
- }
168
173
  else if (event.type === 'assistant/message' && data.usage && typeof data.usage === 'object') {
169
174
  const usage = data.usage;
170
175
  const input = typeof usage.inputTokens === 'number' ? usage.inputTokens : null;
@@ -177,7 +182,7 @@ export function apply(ctx) {
177
182
  const details = await resolveDshStatus(agent.session.header.cwd ?? caller.workspace, session.id, native, process.env.DSH_HOME);
178
183
  const base = stored
179
184
  ? receipt(request, stored.record, await durable(session))
180
- : result(request, 'completed', 'No handoff operation owned by this session', { durable: true, state: 'running' });
185
+ : result(request, 'completed', 'No handoff has been started for this session', { durable: true, state: 'running' });
181
186
  const pointer = await sessionPointer('dsh', agent.session.header.cwd ?? caller.workspace, session.id, (process.env.DSH_HOME ? { dshHome: process.env.DSH_HOME } : {})).catch(() => null);
182
187
  const activity = await sessionActivity(pointer?.path ?? null);
183
188
  const reconciled = reconcileDshStatus(base, details);
@@ -255,8 +260,14 @@ export function apply(ctx) {
255
260
  return decision;
256
261
  const span = replacementSpan(session, fresh, record.boundary);
257
262
  const before = identity(agent);
258
- const proof = { source: record.owner, successor: { ...before, generation: String(session.surface.contentGeneration + 1) }, mechanism: 'new-session', nativeEvidence: `session:${session.id}:event:${session.seq}` };
259
- const applied = { ...record, phase: 'applied', proof, reason: 'Fresh context applied; successor binding recorded' };
263
+ // The surface replacement keeps the native session; only the generation
264
+ // advances. A changed session here would be a false same-SID success.
265
+ if (before.session !== record.owner.session)
266
+ throw new Error('DSH handoff changed the native session id; no transition scheduled');
267
+ const successor = { ...before, session: record.owner.session, generation: String(session.surface.contentGeneration + 1) };
268
+ const proofMechanism = 'surface-replacement';
269
+ const proof = { source: record.owner, successor, mechanism: proofMechanism, nativeEvidence: `session:${session.id}:event:${session.seq}` };
270
+ const applied = { ...record, phase: 'applied', proof, proofMechanism, reason: 'Fresh context applied in the same session; successor binding recorded' };
260
271
  const continuation = {
261
272
  id: randomUUID(), role: 'user',
262
273
  content: [{ type: 'text', text: `AI4AI handoff applied. Continue the caller-provided task in this fresh context. Native system instructions, permissions and policies still apply.\n\n${record.task}` }],
@@ -12,6 +12,10 @@ export interface LaunchSpec {
12
12
  cwd: string;
13
13
  taskFile: string;
14
14
  sessionRegex?: string;
15
+ /** The adapter pre-built the complete cmd.exe command line. */
16
+ windowsVerbatimArguments?: boolean;
17
+ /** Protocol spoken by the supervisor launched here (2 = per-turn resume). */
18
+ supervisorProtocol?: number;
15
19
  }
16
20
  export interface ExecutorStatus {
17
21
  state: string;
@@ -25,6 +29,10 @@ export interface ExecutorStatus {
25
29
  /** Written by the supervisor on child output/events; never self-reported. */
26
30
  lastActivityAt?: string;
27
31
  lastActivitySource?: 'native';
32
+ /** The supervisor's own pid; the child harness pid is `pid`. */
33
+ supervisorPid?: number;
34
+ /** Supervisor protocol version; v0.0.3 supervisors omit it. */
35
+ protocol?: number;
28
36
  }
29
37
  export interface LogLine {
30
38
  ts: string;
@@ -52,12 +60,27 @@ export declare function writeAtomic(file: string, value: unknown): Promise<void>
52
60
  export declare function pidAlive(pid: number | undefined): boolean;
53
61
  export declare function readStatus(home: string, executorId: string): Promise<ExecutorStatus | undefined>;
54
62
  export declare function readLog(home: string, executorId: string, lines?: number): Promise<LogLine[]>;
55
- export declare function enqueueTurn(home: string, executorId: string, turn: {
63
+ export interface QueuedTurn {
56
64
  inputFile?: string;
65
+ command?: string;
66
+ args?: string[];
67
+ windowsVerbatimArguments?: boolean;
57
68
  extraArgs?: string[];
58
- }): Promise<void>;
69
+ }
70
+ /**
71
+ * Publish one message as its own inbox file using O_EXCL.
72
+ *
73
+ * One file per message means concurrent enqueues never read-modify-write the
74
+ * same object, and the supervisor claims a message with an atomic rename. The
75
+ * timestamp prefix preserves arrival order; the uuid suffix makes the name
76
+ * unique under concurrent writers.
77
+ */
78
+ export declare function enqueueTurn(home: string, executorId: string, turn: QueuedTurn): Promise<string>;
79
+ /** Where a queued message currently sits: still pending, claimed, or consumed. */
80
+ export declare function turnPlacement(home: string, executorId: string, name: string): Promise<'pending' | 'claimed' | 'consumed'>;
59
81
  export declare function requestStop(home: string, executorId: string): Promise<void>;
60
82
  export declare function markStoppedIfDead(home: string, executorId: string, status: ExecutorStatus): Promise<ExecutorStatus>;
83
+ export declare function persistedEnv(env: Record<string, string> | undefined): Record<string, string> | undefined;
61
84
  /**
62
85
  * Start a detached supervisor. The supervisor, not the caller, owns the harness
63
86
  * process, so closing the caller's session or killing the caller cannot end it.
@@ -1,6 +1,7 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { existsSync, readFileSync } from 'node:fs';
3
- import { mkdir, readFile, rename, writeFile, appendFile, open } from 'node:fs/promises';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { mkdir, readFile, rename, writeFile, open } from 'node:fs/promises';
4
5
  import path from 'node:path';
5
6
  import { fileURLToPath } from 'node:url';
6
7
  /**
@@ -102,8 +103,44 @@ export async function readLog(home, executorId, lines = 200) {
102
103
  return [];
103
104
  }
104
105
  }
106
+ /**
107
+ * Publish one message as its own inbox file using O_EXCL.
108
+ *
109
+ * One file per message means concurrent enqueues never read-modify-write the
110
+ * same object, and the supervisor claims a message with an atomic rename. The
111
+ * timestamp prefix preserves arrival order; the uuid suffix makes the name
112
+ * unique under concurrent writers.
113
+ */
105
114
  export async function enqueueTurn(home, executorId, turn) {
106
- await appendFile(path.join(executorDir(home, executorId), 'inbox.jsonl'), JSON.stringify(turn) + '\n');
115
+ const directory = path.join(executorDir(home, executorId), 'inbox');
116
+ await mkdir(directory, { recursive: true, mode: 0o700 });
117
+ const name = `${String(Date.now()).padStart(13, '0')}-${randomUUID()}.json`;
118
+ const handle = await open(path.join(directory, name), 'wx', 0o600);
119
+ try {
120
+ await handle.writeFile(JSON.stringify(turn) + '\n');
121
+ }
122
+ finally {
123
+ await handle.close();
124
+ }
125
+ return name;
126
+ }
127
+ /** Where a queued message currently sits: still pending, claimed, or consumed. */
128
+ export async function turnPlacement(home, executorId, name) {
129
+ const directory = executorDir(home, executorId);
130
+ const exists = async (file) => {
131
+ try {
132
+ await open(file, 'r').then(handle => handle.close());
133
+ return true;
134
+ }
135
+ catch {
136
+ return false;
137
+ }
138
+ };
139
+ if (await exists(path.join(directory, 'inbox', name)))
140
+ return 'pending';
141
+ if (await exists(path.join(directory, 'inbox', 'claimed', name)))
142
+ return 'claimed';
143
+ return 'consumed';
107
144
  }
108
145
  export async function requestStop(home, executorId) {
109
146
  await writeAtomic(path.join(executorDir(home, executorId), 'control.json'), { stop: true, requestedAt: new Date().toISOString() });
@@ -123,6 +160,16 @@ export async function markStoppedIfDead(home, executorId, status) {
123
160
  return next;
124
161
  }
125
162
  }
163
+ // Provider credentials must reach the detached carrier through the supervisor's
164
+ // process environment, never through spec.json on disk. Keep non-secret carrier
165
+ // settings (DSH_HOME, PATH, HOME, ...) in the spec; filter API keys/tokens.
166
+ const SENSITIVE_ENV = /(?:^|_)(?:API_KEY|TOKEN|SECRET|PASSWORD|AUTH|CREDENTIALS?)(?:$|_)/i;
167
+ export function persistedEnv(env) {
168
+ if (!env)
169
+ return undefined;
170
+ const kept = Object.fromEntries(Object.entries(env).filter(([key]) => !SENSITIVE_ENV.test(key)));
171
+ return Object.keys(kept).length ? kept : undefined;
172
+ }
126
173
  /**
127
174
  * Start a detached supervisor. The supervisor, not the caller, owns the harness
128
175
  * process, so closing the caller's session or killing the caller cannot end it.
@@ -132,13 +179,16 @@ export async function launch(spec) {
132
179
  await mkdir(directory, { recursive: true });
133
180
  const task = await readFile(spec.taskFile, 'utf8');
134
181
  await writeFile(path.join(directory, 'task.md'), task);
182
+ const persisted = persistedEnv(spec.env);
135
183
  await writeAtomic(path.join(directory, 'spec.json'), {
136
184
  command: spec.command,
137
185
  args: spec.args,
138
- ...(spec.env ? { env: spec.env } : {}),
186
+ ...(persisted ? { env: persisted } : {}),
139
187
  cwd: spec.cwd,
140
188
  inputFile: 'task.prompt',
141
189
  ...(spec.sessionRegex ? { sessionRegex: spec.sessionRegex } : {}),
190
+ ...(spec.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}),
191
+ supervisorProtocol: spec.supervisorProtocol ?? 2,
142
192
  });
143
193
  // The task file the supervisor feeds on stdin is the plain prompt.
144
194
  await writeFile(path.join(directory, 'task.prompt'), task);
@@ -149,7 +199,11 @@ export async function launch(spec) {
149
199
  for (const [key, value] of Object.entries(process.env))
150
200
  if (value !== undefined && !spec.envExclude?.includes(key))
151
201
  env[key] = value;
152
- const fullEnv = { ...env, ...(spec.env ?? {}), AI4AI_EXECUTOR_ID: spec.executorId, AI4AI_EXECUTOR_DIR: directory };
202
+ // The carrier runs with `cwd: spec.cwd`, but an inherited PWD can still name
203
+ // the caller's directory. Harnesses such as OpenCode resolve their project
204
+ // config through PWD, so a detached executor started with --workspace from
205
+ // another directory would load the wrong config and fail every provider call.
206
+ const fullEnv = { ...env, ...(spec.env ?? {}), PWD: spec.cwd, AI4AI_EXECUTOR_ID: spec.executorId, AI4AI_EXECUTOR_DIR: directory };
153
207
  await writeAtomic(path.join(directory, 'launch.json'), { runtime, supervisor, at: new Date().toISOString() });
154
208
  const child = spawn(runtime, [supervisor, '--dir', directory], {
155
209
  detached: true,
@@ -10,6 +10,8 @@ export interface CarrierCommand {
10
10
  env?: Record<string, string>;
11
11
  envExclude?: string[];
12
12
  sessionRegex?: string;
13
+ /** Windows only: the adapter already formed the complete cmd.exe payload. */
14
+ windowsVerbatimArguments?: boolean;
13
15
  }
14
16
  export interface StatusDetails {
15
17
  model?: string | null;
@@ -37,12 +39,31 @@ export declare abstract class ExternalExecutorAdapter implements Adapter {
37
39
  protected abstract carrier(request: Request, ctx: AdapterContext, executorId: string, resumeSessionId?: string): Promise<CarrierCommand>;
38
40
  /** Adapter-specific context/model/reasoning-effort extraction from the carrier output. */
39
41
  protected statusDetails(_record: ExecutorRecord, _status: ExecutorStatus, _log: LogLine[], _ctx: AdapterContext): StatusDetails | Promise<StatusDetails>;
42
+ /**
43
+ * Model a resumed turn must keep: the explicit request override, or the
44
+ * effective value the carrier would use (environment/settings). Persisted at
45
+ * spawn time so a follow-up turn started by a supervisor whose caller lacked
46
+ * that environment still selects the same model.
47
+ */
48
+ protected persistedModel(request: Request, _ctx: AdapterContext): string | undefined | Promise<string | undefined>;
49
+ /** Reasoning effort the resumed turn must keep (same rationale as persistedModel). */
50
+ protected persistedReasoningEffort(request: Request, _ctx: AdapterContext): string | undefined | Promise<string | undefined>;
40
51
  protected writeTask(ctx: AdapterContext, executorId: string, name: string, text: string): Promise<string>;
41
52
  handoff(request: Request, _ctx: AdapterContext): Promise<NativeOutcome>;
42
53
  spawn(request: Request, ctx: AdapterContext): Promise<NativeOutcome>;
43
54
  private executorFor;
44
55
  status(request: Request, ctx: AdapterContext): Promise<NativeOutcome>;
56
+ /**
57
+ * Deliver a follow-up turn to an owned executor.
58
+ *
59
+ * Only a running executor with a live protocol-2 supervisor is served: the
60
+ * turn is queued for that supervisor and resumes the same native session.
61
+ * Idle/exited executors fail structurally instead of silently starting a new
62
+ * session (which would lose the previous context).
63
+ */
45
64
  message(request: Request, ctx: AdapterContext): Promise<NativeOutcome>;
65
+ /** Bounded wait for the carrier's session id; never guesses or reuses first-turn args. */
66
+ private awaitSessionId;
46
67
  cancel(request: Request, ctx: AdapterContext): Promise<NativeOutcome>;
47
68
  /**
48
69
  * Observe an executor from durable state, always cross-checking pid liveness: