operon-agents-core 0.1.0-alpha.2 → 0.1.0-alpha.21

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 (289) hide show
  1. package/dist/agent/agent.d.ts +8 -7
  2. package/dist/agent/compose-hooks.d.ts +10 -1
  3. package/dist/agent/compose-hooks.js +61 -6
  4. package/dist/agent/concurrency.js +1 -1
  5. package/dist/agent/context-report.d.ts +2 -2
  6. package/dist/agent/durable-state.d.ts +22 -0
  7. package/dist/agent/durable-state.js +54 -0
  8. package/dist/agent/index.d.ts +2 -2
  9. package/dist/agent/index.js +1 -1
  10. package/dist/agent/instruction-context.d.ts +6 -6
  11. package/dist/agent/instruction-context.js +23 -23
  12. package/dist/agent/profile-builtins.js +1 -1
  13. package/dist/agent/run-support.d.ts +1 -1
  14. package/dist/agent/run-support.js +6 -5
  15. package/dist/agent/runner.d.ts +25 -22
  16. package/dist/agent/runner.js +217 -121
  17. package/dist/agent/session.d.ts +262 -156
  18. package/dist/agent/session.js +590 -418
  19. package/dist/agent/subagent-tools.js +3 -3
  20. package/dist/agent/subagent.js +28 -13
  21. package/dist/agent/toolset.d.ts +1 -0
  22. package/dist/agent/toolset.js +13 -7
  23. package/dist/agent/workflow/journal.d.ts +2 -2
  24. package/dist/agent/workflow/journal.js +2 -2
  25. package/dist/agent/workflow/manager.d.ts +1 -1
  26. package/dist/agent/workflow/manager.js +1 -1
  27. package/dist/agent/workflow/prompt.js +2 -2
  28. package/dist/agent/workflow/sandbox.d.ts +1 -1
  29. package/dist/agent/workflow/sandbox.js +1 -1
  30. package/dist/agent/workflow/tool.js +30 -43
  31. package/dist/agent/worktree.d.ts +8 -8
  32. package/dist/agent/worktree.js +15 -15
  33. package/dist/capabilities/assembler.d.ts +29 -5
  34. package/dist/capabilities/assembler.js +85 -9
  35. package/dist/capabilities/background/code-task.d.ts +43 -0
  36. package/dist/capabilities/background/code-task.js +75 -0
  37. package/dist/capabilities/background/command-task.d.ts +9 -2
  38. package/dist/capabilities/background/command-task.js +22 -6
  39. package/dist/capabilities/background/index.d.ts +6 -1
  40. package/dist/capabilities/background/index.js +26 -20
  41. package/dist/capabilities/background/manager.d.ts +57 -1
  42. package/dist/capabilities/background/manager.js +210 -45
  43. package/dist/capabilities/background/persist-disk.d.ts +1 -1
  44. package/dist/capabilities/background/persist-disk.js +1 -1
  45. package/dist/capabilities/background/persist.js +4 -2
  46. package/dist/capabilities/background/projections.d.ts +16 -0
  47. package/dist/capabilities/background/projections.js +86 -0
  48. package/dist/capabilities/background/stall-watchdog.d.ts +41 -0
  49. package/dist/capabilities/background/stall-watchdog.js +85 -0
  50. package/dist/capabilities/background/task.d.ts +8 -7
  51. package/dist/capabilities/background/tools.js +33 -7
  52. package/dist/capabilities/capability-data.d.ts +52 -0
  53. package/dist/capabilities/capability-data.js +88 -0
  54. package/dist/capabilities/capability-state.d.ts +2 -4
  55. package/dist/capabilities/capability-state.js +5 -23
  56. package/dist/capabilities/capability.d.ts +203 -38
  57. package/dist/capabilities/compaction/index.js +10 -4
  58. package/dist/capabilities/compaction/service.d.ts +20 -5
  59. package/dist/capabilities/compaction/service.js +27 -11
  60. package/dist/capabilities/goal/goal-store.d.ts +76 -12
  61. package/dist/capabilities/goal/goal-store.js +137 -53
  62. package/dist/capabilities/goal/index.d.ts +1 -1
  63. package/dist/capabilities/goal/index.js +30 -7
  64. package/dist/capabilities/index.d.ts +9 -6
  65. package/dist/capabilities/index.js +4 -3
  66. package/dist/capabilities/plan/index.js +22 -5
  67. package/dist/capabilities/plan/plan-mode.d.ts +30 -9
  68. package/dist/capabilities/plan/plan-mode.js +57 -32
  69. package/dist/capabilities/plan/tools.js +1 -1
  70. package/dist/capabilities/skills/flow-provider.js +3 -3
  71. package/dist/capabilities/skills/index.d.ts +13 -1
  72. package/dist/capabilities/skills/index.js +30 -21
  73. package/dist/capabilities/skills/parser.d.ts +2 -2
  74. package/dist/capabilities/skills/parser.js +3 -3
  75. package/dist/capabilities/skills/registry.d.ts +5 -6
  76. package/dist/capabilities/skills/registry.js +6 -9
  77. package/dist/capabilities/skills/scanner.d.ts +3 -3
  78. package/dist/capabilities/skills/scanner.js +14 -14
  79. package/dist/capabilities/skills/service.d.ts +2 -1
  80. package/dist/capabilities/skills/service.js +3 -3
  81. package/dist/capabilities/skills/skill-tool.d.ts +2 -0
  82. package/dist/capabilities/skills/skill-tool.js +1 -1
  83. package/dist/capabilities/task/index.js +2 -1
  84. package/dist/capabilities/task/persist-disk.d.ts +1 -1
  85. package/dist/capabilities/task/persist-disk.js +1 -1
  86. package/dist/capabilities/task/persist.js +1 -1
  87. package/dist/capabilities/todo/index.js +11 -6
  88. package/dist/capabilities/todo/injector.js +2 -1
  89. package/dist/capabilities/todo/todo-store.d.ts +28 -7
  90. package/dist/capabilities/todo/todo-store.js +44 -11
  91. package/dist/capabilities/todo/tools.js +8 -3
  92. package/dist/capabilities/tool-provider.d.ts +3 -3
  93. package/dist/capabilities/user-hooks/engine.d.ts +3 -3
  94. package/dist/capabilities/user-hooks/engine.js +7 -7
  95. package/dist/capabilities/user-hooks/index.js +2 -1
  96. package/dist/capabilities/workflow/index.d.ts +5 -3
  97. package/dist/capabilities/workflow/index.js +3 -2
  98. package/dist/commands/index.js +34 -32
  99. package/dist/config/index.d.ts +1 -1
  100. package/dist/config/provider-manager.js +0 -28
  101. package/dist/config/schema.d.ts +53 -4
  102. package/dist/config/schema.js +53 -1
  103. package/dist/events/events.d.ts +43 -11
  104. package/dist/events/events.js +1 -0
  105. package/dist/events/index.d.ts +2 -2
  106. package/dist/events/index.js +1 -1
  107. package/dist/events/projection.d.ts +49 -1
  108. package/dist/events/projection.js +144 -19
  109. package/dist/events/publisher.js +2 -21
  110. package/dist/home.d.ts +1 -1
  111. package/dist/home.js +1 -1
  112. package/dist/index.d.ts +3 -2
  113. package/dist/index.js +2 -1
  114. package/dist/internal.d.ts +5 -2
  115. package/dist/internal.js +5 -2
  116. package/dist/llm/define-model.d.ts +4 -0
  117. package/dist/llm/define-model.js +63 -25
  118. package/dist/llm/index.d.ts +1 -0
  119. package/dist/llm/index.js +1 -0
  120. package/dist/llm/model.d.ts +2 -0
  121. package/dist/llm/provider.d.ts +17 -0
  122. package/dist/llm/provider.js +14 -0
  123. package/dist/llm/retry.js +1 -1
  124. package/dist/loop/context.d.ts +21 -1
  125. package/dist/loop/context.js +47 -9
  126. package/dist/loop/events.d.ts +5 -1
  127. package/dist/loop/index.d.ts +2 -2
  128. package/dist/loop/index.js +1 -1
  129. package/dist/loop/interruption.d.ts +9 -4
  130. package/dist/loop/interruption.js +11 -25
  131. package/dist/loop/run-turn.d.ts +16 -3
  132. package/dist/loop/run-turn.js +13 -4
  133. package/dist/loop/steer.d.ts +78 -12
  134. package/dist/loop/steer.js +101 -38
  135. package/dist/loop/tool-call.d.ts +13 -2
  136. package/dist/loop/tool-call.js +135 -5
  137. package/dist/loop/turn-step.d.ts +13 -2
  138. package/dist/loop/turn-step.js +29 -7
  139. package/dist/loop/types.d.ts +6 -0
  140. package/dist/mcp/auth-tool.d.ts +3 -1
  141. package/dist/mcp/auth-tool.js +2 -2
  142. package/dist/mcp/capability.d.ts +13 -0
  143. package/dist/mcp/capability.js +36 -17
  144. package/dist/mcp/config-loader.d.ts +5 -5
  145. package/dist/mcp/config-loader.js +17 -17
  146. package/dist/mcp/credentials.d.ts +35 -0
  147. package/dist/mcp/credentials.js +2 -0
  148. package/dist/mcp/filter.d.ts +2 -2
  149. package/dist/mcp/index.d.ts +4 -3
  150. package/dist/mcp/index.js +1 -1
  151. package/dist/mcp/manager.d.ts +108 -6
  152. package/dist/mcp/manager.js +262 -18
  153. package/dist/mcp/oauth/callback-server.d.ts +10 -1
  154. package/dist/mcp/oauth/callback-server.js +82 -16
  155. package/dist/mcp/oauth/index.d.ts +2 -2
  156. package/dist/mcp/oauth/provider.d.ts +18 -0
  157. package/dist/mcp/oauth/provider.js +31 -1
  158. package/dist/mcp/oauth/service.d.ts +9 -3
  159. package/dist/mcp/oauth/service.js +29 -4
  160. package/dist/mcp/sdk-transport.js +1 -1
  161. package/dist/mcp/server.js +1 -1
  162. package/dist/permission/auto-approver/prompts-data.d.ts +1 -1
  163. package/dist/permission/auto-approver/prompts-data.js +1 -1
  164. package/dist/permission/manager.d.ts +5 -3
  165. package/dist/permission/manager.js +7 -3
  166. package/dist/permission/policies.d.ts +2 -2
  167. package/dist/permission/policies.js +4 -4
  168. package/dist/plugins/fields.d.ts +14 -0
  169. package/dist/plugins/fields.js +30 -0
  170. package/dist/plugins/hooks.d.ts +2 -2
  171. package/dist/plugins/hooks.js +12 -12
  172. package/dist/plugins/index.js +1 -0
  173. package/dist/plugins/manager.d.ts +8 -3
  174. package/dist/plugins/manager.js +18 -7
  175. package/dist/plugins/manifest.d.ts +2 -2
  176. package/dist/plugins/manifest.js +101 -91
  177. package/dist/plugins/marketplace.js +76 -57
  178. package/dist/plugins/store.d.ts +3 -3
  179. package/dist/plugins/store.js +6 -6
  180. package/dist/protocol/index.d.ts +1 -1
  181. package/dist/store/catalog-store.d.ts +4 -1
  182. package/dist/store/catalog-store.js +5 -1
  183. package/dist/store/checkpointing-store.d.ts +41 -0
  184. package/dist/store/checkpointing-store.js +86 -0
  185. package/dist/store/disk-store.d.ts +8 -0
  186. package/dist/store/disk-store.js +127 -5
  187. package/dist/store/index.d.ts +3 -2
  188. package/dist/store/index.js +2 -1
  189. package/dist/store/log-store.d.ts +9 -1
  190. package/dist/store/log-store.js +68 -4
  191. package/dist/store/migrate.d.ts +8 -2
  192. package/dist/store/migrate.js +9 -2
  193. package/dist/store/origin.d.ts +31 -6
  194. package/dist/store/origin.js +0 -14
  195. package/dist/store/pg.d.ts +1 -0
  196. package/dist/store/pg.js +37 -2
  197. package/dist/store/redis.d.ts +1 -0
  198. package/dist/store/redis.js +30 -0
  199. package/dist/store/repository.d.ts +13 -1
  200. package/dist/store/repository.js +45 -2
  201. package/dist/store/session-catalog.d.ts +4 -0
  202. package/dist/store/session-catalog.js +6 -0
  203. package/dist/store/storage.js +3 -0
  204. package/dist/store/store.d.ts +97 -34
  205. package/dist/store/store.js +64 -10
  206. package/dist/telemetry/appender.d.ts +43 -0
  207. package/dist/telemetry/appender.js +46 -0
  208. package/dist/telemetry/events.d.ts +142 -0
  209. package/dist/telemetry/events.js +141 -0
  210. package/dist/telemetry/index.d.ts +10 -0
  211. package/dist/telemetry/index.js +6 -0
  212. package/dist/telemetry/projection.d.ts +23 -0
  213. package/dist/telemetry/projection.js +185 -0
  214. package/dist/telemetry/redact.d.ts +20 -0
  215. package/dist/telemetry/redact.js +40 -0
  216. package/dist/telemetry/service.d.ts +49 -0
  217. package/dist/telemetry/service.js +137 -0
  218. package/dist/testing.d.ts +58 -0
  219. package/dist/testing.js +123 -0
  220. package/dist/tool/background.d.ts +9 -6
  221. package/dist/tool/background.js +7 -1
  222. package/dist/tool/builtin/ask-user-question.js +6 -5
  223. package/dist/tool/builtin/bash.d.ts +6 -0
  224. package/dist/tool/builtin/bash.js +79 -42
  225. package/dist/tool/builtin/edit.js +82 -109
  226. package/dist/tool/builtin/glob.js +13 -13
  227. package/dist/tool/builtin/grep.js +13 -13
  228. package/dist/tool/builtin/read.js +25 -15
  229. package/dist/tool/builtin/write.js +49 -33
  230. package/dist/tool/define.d.ts +14 -8
  231. package/dist/tool/define.js +8 -2
  232. package/dist/tool/{machine-base.d.ts → environment-base.d.ts} +37 -37
  233. package/dist/tool/{machine-base.js → environment-base.js} +45 -119
  234. package/dist/tool/{machine-local.d.ts → environment-local.d.ts} +9 -8
  235. package/dist/tool/{machine-local.js → environment-local.js} +60 -81
  236. package/dist/tool/{machine-null.d.ts → environment-null.d.ts} +9 -9
  237. package/dist/tool/{machine-null.js → environment-null.js} +9 -9
  238. package/dist/tool/{machine-ssh.d.ts → environment-ssh.d.ts} +33 -18
  239. package/dist/tool/{machine-ssh.js → environment-ssh.js} +118 -149
  240. package/dist/tool/{machine.d.ts → environment.d.ts} +53 -82
  241. package/dist/tool/environment.js +2 -0
  242. package/dist/tool/file-freshness.d.ts +33 -19
  243. package/dist/tool/file-freshness.js +39 -30
  244. package/dist/tool/filesystem-tools.d.ts +1 -1
  245. package/dist/tool/filesystem-tools.js +1 -1
  246. package/dist/tool/git-context.d.ts +2 -2
  247. package/dist/tool/git-context.js +8 -8
  248. package/dist/tool/index.d.ts +12 -12
  249. package/dist/tool/index.js +12 -10
  250. package/dist/tool/policies/path-access.d.ts +4 -4
  251. package/dist/tool/policies/path-access.js +12 -12
  252. package/dist/tool/questions.d.ts +8 -0
  253. package/dist/tool/search/catalog.d.ts +37 -0
  254. package/dist/tool/search/catalog.js +182 -0
  255. package/dist/tool/search/deferral.d.ts +3 -2
  256. package/dist/tool/search/loaded.d.ts +32 -0
  257. package/dist/tool/search/loaded.js +96 -0
  258. package/dist/tool/search/search-tool.d.ts +2 -6
  259. package/dist/tool/search/search-tool.js +16 -15
  260. package/dist/tool/shell-env.js +4 -0
  261. package/dist/tool/support/bash-paths.js +38 -7
  262. package/dist/tool/support/{machine-ops.d.ts → environment-ops.d.ts} +12 -14
  263. package/dist/tool/support/{machine-ops.js → environment-ops.js} +21 -2
  264. package/dist/tool/support/git-worktree.d.ts +3 -3
  265. package/dist/tool/support/git-worktree.js +6 -6
  266. package/dist/tool/support/rg-locator.d.ts +6 -6
  267. package/dist/tool/support/rg-locator.js +6 -6
  268. package/dist/tool/support/ripgrep-run.d.ts +5 -5
  269. package/dist/tool/support/ripgrep-run.js +3 -3
  270. package/dist/tool/support/tool-path.d.ts +3 -3
  271. package/dist/tool/support/tool-path.js +7 -7
  272. package/dist/tool/types.d.ts +54 -10
  273. package/dist/tool/web/fetch-url.js +1 -1
  274. package/dist/tool/web/web-search.js +1 -1
  275. package/dist/tool/workspace-spec.d.ts +3 -3
  276. package/dist/tool/workspace-spec.js +27 -27
  277. package/dist/tracing/bridge.d.ts +9 -1
  278. package/dist/tracing/bridge.js +307 -77
  279. package/dist/tracing/index.d.ts +2 -2
  280. package/dist/tracing/otel.d.ts +28 -1
  281. package/dist/tracing/otel.js +150 -38
  282. package/dist/tracing/processor.d.ts +22 -0
  283. package/dist/tracing/processor.js +2 -0
  284. package/dist/tracing/spans.d.ts +54 -0
  285. package/dist/tracing/spans.js +5 -0
  286. package/package.json +6 -2
  287. package/dist/tool/machine.js +0 -15
  288. package/dist/tool/search/activation.d.ts +0 -13
  289. package/dist/tool/search/activation.js +0 -31
@@ -1,9 +1,9 @@
1
1
  import { type Readable, type Writable } from "node:stream";
2
2
  import type { Client, ClientChannel, ConnectConfig, SFTPWrapper } from "ssh2";
3
- import { type Environment, type ByteRange, type Machine, type DirEntry, type FileInfo, type WriteFileResult, type WriteTextIfUnchangedOptions } from "./machine.ts";
4
- import { BaseMachine, type SpawnedProcess } from "./machine-base.ts";
5
- export type SshMachineExtraOptions = Omit<ConnectConfig, "host" | "port" | "username" | "password" | "privateKey" | "authHandler" | "hostVerifier">;
6
- export interface SshMachineOptions {
3
+ import { type OsInfo, type ByteRange, type Environment, type DirEntry, type FileInfo } from "./environment.ts";
4
+ import { BaseEnvironment, type SpawnedProcess } from "./environment-base.ts";
5
+ export type SshEnvironmentExtraOptions = Omit<ConnectConfig, "host" | "port" | "username" | "password" | "privateKey" | "authHandler" | "hostVerifier">;
6
+ export interface SshEnvironmentOptions {
7
7
  readonly host: string;
8
8
  readonly port?: number;
9
9
  readonly username: string;
@@ -11,15 +11,26 @@ export interface SshMachineOptions {
11
11
  readonly keyPaths?: readonly string[];
12
12
  readonly keyContents?: readonly string[];
13
13
  readonly cwd?: string;
14
- /** Extra workspace roots granted cwd-equivalent path access (see Machine.additionalDirs). */
14
+ /** Extra workspace roots granted cwd-equivalent path access (see Environment.additionalDirs). */
15
15
  readonly additionalDirs?: readonly string[];
16
16
  readonly name?: string;
17
17
  readonly hostVerifier?: (key: Buffer) => boolean;
18
18
  readonly forwardProxyEnv?: boolean;
19
- readonly extraOptions?: SshMachineExtraOptions;
19
+ readonly extraOptions?: SshEnvironmentExtraOptions;
20
20
  }
21
21
  export declare function sshShellQuote(arg: string): string;
22
22
  export declare function buildSshExecCommand(args: readonly string[], cwd: string, env?: Record<string, string>): string;
23
+ /**
24
+ * Prefix that makes a remote command report its process group before it runs.
25
+ *
26
+ * sshd starts an exec request as `$SHELL -c '<command>'` in a new session, so that shell leads
27
+ * the process group everything the command starts belongs to — and its pid is the group id. A
28
+ * child `sh` reads it back as `$PPID`: the login shell may not be POSIX (fish has no `$$`), but
29
+ * `sh -c '…'` parses the same everywhere.
30
+ */
31
+ export declare const SSH_PGID_REPORT = "sh -c 'printf \"%s%s\\n\" __OPERON_PGID__= \"$PPID\"' >&2; ";
32
+ /** A short side command on the same connection, resolving with its exit code. */
33
+ export type SshSideExec = (command: string) => Promise<number>;
23
34
  export declare class SshProcess implements SpawnedProcess {
24
35
  readonly stdin: Writable;
25
36
  readonly stdout: Readable;
@@ -27,14 +38,21 @@ export declare class SshProcess implements SpawnedProcess {
27
38
  private _exitCode;
28
39
  private readonly _exit;
29
40
  private readonly channel;
30
- constructor(channel: ClientChannel);
41
+ private readonly sideExec;
42
+ private pgid;
43
+ /**
44
+ * `sideExec` present = the command was started behind {@link SSH_PGID_REPORT}: stderr carries
45
+ * the group id, and a stop signals the whole group through a second exec on the connection.
46
+ * Without it only the channel is signalled, which sshd delivers to the login shell alone.
47
+ */
48
+ constructor(channel: ClientChannel, sideExec?: SshSideExec);
31
49
  get exitCode(): number | null;
32
50
  wait(): Promise<number>;
33
51
  kill(signal?: NodeJS.Signals): Promise<void>;
34
52
  }
35
- export declare class SshMachine extends BaseMachine {
53
+ export declare class SshEnvironment extends BaseEnvironment {
36
54
  readonly name: string;
37
- readonly osEnv: Environment;
55
+ readonly osInfo: OsInfo;
38
56
  private readonly client;
39
57
  private readonly sftp;
40
58
  private readonly home;
@@ -47,12 +65,12 @@ export declare class SshMachine extends BaseMachine {
47
65
  sftp: SFTPWrapper;
48
66
  home: string;
49
67
  cwd?: string;
50
- osEnv: Environment;
68
+ osInfo: OsInfo;
51
69
  name?: string;
52
70
  injectedEnv?: Record<string, string>;
53
71
  additionalDirs?: readonly string[];
54
- }): SshMachine;
55
- static create(options: SshMachineOptions): Promise<SshMachine>;
72
+ }): SshEnvironment;
73
+ static create(options: SshEnvironmentOptions): Promise<SshEnvironment>;
56
74
  pathClass(): "posix" | "win32";
57
75
  normpath(path: string): string;
58
76
  gethome(): string;
@@ -65,15 +83,12 @@ export declare class SshMachine extends BaseMachine {
65
83
  /** SFTP readdir returns each entry's attrs (lstat semantics) alongside its name, so the
66
84
  * whole listing — kinds included — is a single round trip. */
67
85
  listDir(path: string): Promise<readonly DirEntry[]>;
68
- withCwd(cwd: string): Machine;
86
+ withCwd(cwd: string): Environment;
69
87
  readBytes(path: string, range?: ByteRange): Promise<Buffer>;
70
88
  /** Streamed via SFTP + the shared scanner: bounded memory ("read the last 10 lines"
71
89
  * no longer pulls the whole file into a Buffer), same range/byte-cap semantics as
72
- * LocalMachine's streaming path — replaces the whole-file BaseMachine composition. */
90
+ * LocalEnvironment's streaming path — replaces the whole-file BaseEnvironment composition. */
73
91
  protected writeBytesRaw(path: string, data: Buffer): Promise<void>;
74
- /** Same file → same lock across path spellings: resolve against cwd like every SFTP call does. */
75
- protected lockKeyFor(path: string): string;
76
- writeTextIfUnchanged(path: string, data: string, options: WriteTextIfUnchangedOptions): Promise<WriteFileResult>;
77
92
  /** SFTP has a native canonicalizer — exact, no readlink dependency. */
78
93
  realpath(path: string): Promise<string>;
79
94
  mkdir(path: string, options?: {
@@ -83,4 +98,4 @@ export declare class SshMachine extends BaseMachine {
83
98
  protected spawn(argv: readonly string[], env?: Record<string, string>): Promise<SpawnedProcess>;
84
99
  close(): Promise<void>;
85
100
  }
86
- //# sourceMappingURL=machine-ssh.d.ts.map
101
+ //# sourceMappingURL=environment-ssh.d.ts.map
@@ -1,11 +1,9 @@
1
- import { randomBytes } from "node:crypto";
2
1
  import { readFile } from "node:fs/promises";
3
- import { PassThrough } from "node:stream";
2
+ import { PassThrough, Transform } from "node:stream";
4
3
  import { posix } from "node:path";
5
4
  import * as ssh2 from "ssh2";
6
- import { FileExistsError, } from "./machine.js";
7
- import { BaseMachine } from "./machine-base.js";
8
- import { fileVersionFromInfo } from "./support/machine-ops.js";
5
+ import {} from "./environment.js";
6
+ import { BaseEnvironment } from "./environment-base.js";
9
7
  import { proxyEnv } from "./shell-env.js";
10
8
  const FALLBACK_SFTP_STATUS = {
11
9
  NO_SUCH_FILE: 2,
@@ -47,7 +45,7 @@ export function buildSshExecCommand(args, cwd, env) {
47
45
  const assignments = [];
48
46
  for (const [key, value] of Object.entries(env)) {
49
47
  if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) {
50
- throw new Error(`SshMachine: invalid env variable name ${JSON.stringify(key)}`);
48
+ throw new Error(`SshEnvironment: invalid env variable name ${JSON.stringify(key)}`);
51
49
  }
52
50
  assignments.push(`${key}=${sshShellQuote(value)}`);
53
51
  }
@@ -67,6 +65,56 @@ function fileKindFromSftpStats(attrs) {
67
65
  return "symlink";
68
66
  return "other";
69
67
  }
68
+ /** First stderr line of every posix command: the process group the command runs in. */
69
+ const PGID_MARKER = "__OPERON_PGID__=";
70
+ /**
71
+ * Prefix that makes a remote command report its process group before it runs.
72
+ *
73
+ * sshd starts an exec request as `$SHELL -c '<command>'` in a new session, so that shell leads
74
+ * the process group everything the command starts belongs to — and its pid is the group id. A
75
+ * child `sh` reads it back as `$PPID`: the login shell may not be POSIX (fish has no `$$`), but
76
+ * `sh -c '…'` parses the same everywhere.
77
+ */
78
+ export const SSH_PGID_REPORT = `sh -c 'printf "%s%s\\n" ${PGID_MARKER} "$PPID"' >&2; `;
79
+ /**
80
+ * Strips the {@link SSH_PGID_REPORT} line off the front of stderr and hands over the group id.
81
+ * Anything that is not the marker passes through untouched, so a server that ignored the
82
+ * prefix costs nothing but the ability to signal the group.
83
+ */
84
+ class PgidMarkerStripper extends Transform {
85
+ pending = Buffer.alloc(0);
86
+ onPgid;
87
+ constructor(onPgid) {
88
+ super();
89
+ this.onPgid = onPgid;
90
+ }
91
+ _transform(chunk, _encoding, callback) {
92
+ if (this.pending === undefined) {
93
+ callback(null, chunk);
94
+ return;
95
+ }
96
+ const buffered = Buffer.concat([this.pending, chunk]);
97
+ const newline = buffered.indexOf(0x0a);
98
+ if (newline === -1 && buffered.length < 256) {
99
+ this.pending = buffered;
100
+ callback();
101
+ return;
102
+ }
103
+ this.pending = undefined;
104
+ const line = newline === -1 ? "" : buffered.subarray(0, newline).toString("utf8");
105
+ const match = line.startsWith(PGID_MARKER) ? /^(\d+)$/.exec(line.slice(PGID_MARKER.length)) : null;
106
+ if (match === null) {
107
+ callback(null, buffered);
108
+ return;
109
+ }
110
+ this.onPgid(Number(match[1]));
111
+ const rest = buffered.subarray(newline + 1);
112
+ callback(null, rest.length > 0 ? rest : undefined);
113
+ }
114
+ _flush(callback) {
115
+ callback(null, this.pending !== undefined && this.pending.length > 0 ? this.pending : undefined);
116
+ }
117
+ }
70
118
  export class SshProcess {
71
119
  stdin;
72
120
  stdout;
@@ -74,16 +122,29 @@ export class SshProcess {
74
122
  _exitCode = null;
75
123
  _exit;
76
124
  channel;
77
- constructor(channel) {
125
+ sideExec;
126
+ pgid;
127
+ /**
128
+ * `sideExec` present = the command was started behind {@link SSH_PGID_REPORT}: stderr carries
129
+ * the group id, and a stop signals the whole group through a second exec on the connection.
130
+ * Without it only the channel is signalled, which sshd delivers to the login shell alone.
131
+ */
132
+ constructor(channel, sideExec) {
78
133
  this.channel = channel;
134
+ this.sideExec = sideExec;
79
135
  this.stdin = channel;
80
136
  // Buffer through PassThroughs so output emitted before a consumer attaches isn't dropped.
81
137
  const out = new PassThrough();
82
- const err = new PassThrough();
83
138
  channel.pipe(out);
84
- channel.stderr.pipe(err);
85
139
  this.stdout = out;
86
- this.stderr = err;
140
+ if (sideExec === undefined) {
141
+ const err = new PassThrough();
142
+ channel.stderr.pipe(err);
143
+ this.stderr = err;
144
+ }
145
+ else {
146
+ this.stderr = channel.stderr.pipe(new PgidMarkerStripper((pgid) => (this.pgid = pgid)));
147
+ }
87
148
  this._exit = new Promise((resolve) => {
88
149
  // Resolve on 'close' (all buffered output flushed); 'exit' carries the code on some backends.
89
150
  channel.on("exit", (code) => {
@@ -101,10 +162,15 @@ export class SshProcess {
101
162
  wait() {
102
163
  return this._exit;
103
164
  }
104
- kill(signal = "SIGTERM") {
165
+ async kill(signal = "SIGTERM") {
105
166
  const sshSignal = signal.startsWith("SIG") ? signal.slice(3) : signal;
167
+ if (this.sideExec !== undefined && this.pgid !== undefined) {
168
+ // The group first, the lone pid if it is not a group leader after all (a server that did
169
+ // not start a new session). Either way the channel signal below still goes out.
170
+ const pgid = String(this.pgid);
171
+ await this.sideExec(`kill -s ${sshSignal} -- -${pgid} 2>/dev/null || kill -s ${sshSignal} ${pgid} 2>/dev/null`).catch(() => undefined);
172
+ }
106
173
  this.channel.signal(sshSignal);
107
- return Promise.resolve();
108
174
  }
109
175
  }
110
176
  function connectClient(config) {
@@ -125,6 +191,19 @@ function clientExec(client, command) {
125
191
  client.exec(command, (err, channel) => (err ? reject(err) : resolve(channel)));
126
192
  });
127
193
  }
194
+ /** Run a command for its exit status alone: output is drained and discarded. */
195
+ async function execForExitCode(client, command) {
196
+ const channel = await clientExec(client, command);
197
+ return await new Promise((resolve) => {
198
+ let code = null;
199
+ channel.on("exit", (exitCode) => {
200
+ code = exitCode;
201
+ });
202
+ channel.on("close", () => resolve(code ?? 1));
203
+ channel.resume();
204
+ channel.stderr.resume();
205
+ });
206
+ }
128
207
  function sftpRealpath(sftp, path) {
129
208
  return new Promise((resolve, reject) => {
130
209
  sftp.realpath(path, (err, abs) => (err ? reject(mapSftpError("realpath", err)) : resolve(abs)));
@@ -150,9 +229,6 @@ function sftpMkdir(sftp, path) {
150
229
  sftp.mkdir(path, (err) => (err ? reject(mapSftpError("mkdir", err)) : resolve()));
151
230
  });
152
231
  }
153
- function sftpExists(sftp, path) {
154
- return new Promise((resolve) => sftp.exists(path, (exists) => resolve(exists)));
155
- }
156
232
  /** Occupant kind probe for mkdir: `exists` alone can't tell a file from a directory, and
157
233
  * mkdir's `existOk`/`parents` semantics only tolerate DIRECTORY occupants. */
158
234
  async function sftpKindOf(sftp, path) {
@@ -196,62 +272,6 @@ function sftpReadHandle(sftp, handle, offset, length) {
196
272
  function sftpClose(sftp, handle) {
197
273
  return new Promise((resolve) => sftp.close(handle, () => resolve()));
198
274
  }
199
- function sftpWriteHandle(sftp, handle, data) {
200
- return new Promise((resolve, reject) => {
201
- // ssh2 chunks writes beyond the server's max packet size internally.
202
- sftp.write(handle, data, 0, data.byteLength, 0, (err) => (err ? reject(mapSftpError("write", err)) : resolve()));
203
- });
204
- }
205
- function sftpCloseHandle(sftp, handle) {
206
- return new Promise((resolve, reject) => {
207
- sftp.close(handle, (err) => (err ? reject(mapSftpError("close", err)) : resolve()));
208
- });
209
- }
210
- function sftpUnlink(sftp, path) {
211
- return new Promise((resolve, reject) => {
212
- sftp.unlink(path, (err) => (err ? reject(mapSftpError("unlink", err)) : resolve()));
213
- });
214
- }
215
- function sftpRename(sftp, src, dst) {
216
- return new Promise((resolve, reject) => {
217
- sftp.rename(src, dst, (err) => (err ? reject(mapSftpError("rename", err)) : resolve()));
218
- });
219
- }
220
- function sftpSetstat(sftp, path, attrs) {
221
- return new Promise((resolve, reject) => {
222
- sftp.setstat(path, attrs, (err) => (err ? reject(mapSftpError("setstat", err)) : resolve()));
223
- });
224
- }
225
- /**
226
- * Atomic overwriting rename: posix-rename@openssh.com when the server offers it.
227
- * ONLY the unsupported-extension error falls back to unlink+rename (which has a tiny
228
- * no-file window between the two calls) — any real failure propagates untouched,
229
- * because unlinking the destination after e.g. a permission error would delete the
230
- * target with no replacement guaranteed.
231
- */
232
- async function sftpAtomicRename(sftp, src, dst) {
233
- try {
234
- await new Promise((resolve, reject) => {
235
- // ssh2 throws synchronously when the server lacks the extension; the
236
- // executor converts that throw into a rejection.
237
- sftp.ext_openssh_rename(src, dst, (err) => (err ? reject(mapSftpError("rename", err)) : resolve()));
238
- });
239
- return;
240
- }
241
- catch (error) {
242
- const unsupported = error instanceof Error && /does not support this extended request/i.test(error.message);
243
- if (!unsupported)
244
- throw error;
245
- }
246
- try {
247
- await sftpUnlink(sftp, dst);
248
- }
249
- catch (error) {
250
- if (error.code !== "ENOENT")
251
- throw error;
252
- }
253
- await sftpRename(sftp, src, dst); // SFTP v3 rename refuses to overwrite — dst is gone by now
254
- }
255
275
  function buildAuthHandler(username, privateKeys, password) {
256
276
  const queue = privateKeys.map((key) => ({ key, type: "publickey", username }));
257
277
  if (password !== undefined)
@@ -265,9 +285,9 @@ function buildAuthHandler(username, privateKeys, password) {
265
285
  }
266
286
  /** Deadline for the env probe: the probe is best-effort (failure already falls back to
267
287
  * defaults), but a server that never closes the exec channel — a restricted shell, an
268
- * unclean close — must not hang `SshMachine.create()` forever. */
288
+ * unclean close — must not hang `SshEnvironment.create()` forever. */
269
289
  const PROBE_TIMEOUT_MS = 10_000;
270
- async function probeRemoteEnvironment(client) {
290
+ async function probeRemoteOsInfo(client) {
271
291
  let raw = "";
272
292
  try {
273
293
  raw = await new Promise((resolve, reject) => {
@@ -290,7 +310,7 @@ async function probeRemoteEnvironment(client) {
290
310
  catch {
291
311
  /* fall through to defaults */
292
312
  }
293
- const [sysname = "", machine = "", osVersion = "", shell = ""] = raw.split("\n").map((line) => line.trim());
313
+ const [sysname = "", environment = "", osVersion = "", shell = ""] = raw.split("\n").map((line) => line.trim());
294
314
  const osKind = /^linux/i.test(sysname)
295
315
  ? "Linux"
296
316
  : /^darwin/i.test(sysname)
@@ -302,11 +322,11 @@ async function probeRemoteEnvironment(client) {
302
322
  : "Linux";
303
323
  const shellPath = shell.length > 0 ? shell : "/bin/sh";
304
324
  const shellName = posix.basename(shellPath);
305
- return { osKind, osArch: machine || "unknown", osVersion: osVersion || "unknown", shellName, shellPath };
325
+ return { osKind, osArch: environment || "unknown", osVersion: osVersion || "unknown", shellName, shellPath };
306
326
  }
307
- export class SshMachine extends BaseMachine {
327
+ export class SshEnvironment extends BaseEnvironment {
308
328
  name;
309
- osEnv;
329
+ osInfo;
310
330
  client;
311
331
  sftp;
312
332
  home;
@@ -319,18 +339,18 @@ export class SshMachine extends BaseMachine {
319
339
  this.sftp = args.sftp;
320
340
  this.home = args.home;
321
341
  this.cwd = args.cwd;
322
- this.osEnv = args.osEnv;
342
+ this.osInfo = args.osInfo;
323
343
  this.name = args.name;
324
344
  this.injectedEnv = args.injectedEnv;
325
345
  this.extraDirs = args.additionalDirs;
326
346
  }
327
347
  static fromConnection(args) {
328
- return new SshMachine({
348
+ return new SshEnvironment({
329
349
  client: args.client,
330
350
  sftp: args.sftp,
331
351
  home: args.home,
332
352
  cwd: args.cwd ?? args.home,
333
- osEnv: args.osEnv,
353
+ osInfo: args.osInfo,
334
354
  name: args.name ?? "ssh",
335
355
  injectedEnv: args.injectedEnv ?? {},
336
356
  additionalDirs: args.additionalDirs ?? [],
@@ -367,9 +387,9 @@ export class SshMachine extends BaseMachine {
367
387
  if (!attrs.isDirectory())
368
388
  throw codedError(`${cwd} is not a directory`, "ENOTDIR");
369
389
  }
370
- const osEnv = await probeRemoteEnvironment(client);
390
+ const osInfo = await probeRemoteOsInfo(client);
371
391
  const injectedEnv = options.forwardProxyEnv === false ? {} : proxyEnv();
372
- return new SshMachine({ client, sftp, home, cwd, osEnv, name: options.name ?? `ssh:${options.host}`, injectedEnv, additionalDirs: options.additionalDirs ?? [] });
392
+ return new SshEnvironment({ client, sftp, home, cwd, osInfo, name: options.name ?? `ssh:${options.host}`, injectedEnv, additionalDirs: options.additionalDirs ?? [] });
373
393
  }
374
394
  catch (error) {
375
395
  client.end();
@@ -415,17 +435,16 @@ export class SshMachine extends BaseMachine {
415
435
  }
416
436
  withCwd(cwd) {
417
437
  // Share this connection's client/sftp — only the cwd differs. Never close the
418
- // clone independently; the connection is owned by whoever opened this machine.
419
- const clone = SshMachine.fromConnection({
438
+ // clone independently; the connection is owned by whoever opened this environment.
439
+ const clone = SshEnvironment.fromConnection({
420
440
  client: this.client,
421
441
  sftp: this.sftp,
422
442
  home: this.home,
423
443
  cwd: this.resolvePath(cwd),
424
- osEnv: this.osEnv,
444
+ osInfo: this.osInfo,
425
445
  name: this.name,
426
446
  injectedEnv: this.injectedEnv,
427
447
  });
428
- clone.pathLocks = this.pathLocks; // one connection, one file namespace — clones share write locks
429
448
  return clone;
430
449
  }
431
450
  async readBytes(path, range) {
@@ -448,63 +467,10 @@ export class SshMachine extends BaseMachine {
448
467
  }
449
468
  /** Streamed via SFTP + the shared scanner: bounded memory ("read the last 10 lines"
450
469
  * no longer pulls the whole file into a Buffer), same range/byte-cap semantics as
451
- * LocalMachine's streaming path — replaces the whole-file BaseMachine composition. */
470
+ * LocalEnvironment's streaming path — replaces the whole-file BaseEnvironment composition. */
452
471
  async writeBytesRaw(path, data) {
453
472
  await sftpWriteFile(this.sftp, this.resolvePath(path), data);
454
473
  }
455
- /** Same file → same lock across path spellings: resolve against cwd like every SFTP call does. */
456
- lockKeyFor(path) {
457
- return this.resolvePath(path);
458
- }
459
- async writeTextIfUnchanged(path, data, options) {
460
- return await this.withPathLock(path, async () => {
461
- const encoding = options.encoding ?? "utf8";
462
- const resolved = this.resolvePath(path);
463
- const payload = options.lineEndings === "CRLF" ? data.replaceAll("\n", "\r\n") : data;
464
- const buf = Buffer.from(payload, encoding);
465
- if (options.expected === "must-not-exist") {
466
- let handle;
467
- try {
468
- handle = await sftpOpen(this.sftp, resolved, "wx");
469
- }
470
- catch (error) {
471
- // SFTP v3 has no EEXIST status (servers report a generic FAILURE) — disambiguate by stat.
472
- if (await sftpExists(this.sftp, resolved))
473
- throw new FileExistsError();
474
- throw error;
475
- }
476
- try {
477
- await sftpWriteHandle(this.sftp, handle, buf);
478
- }
479
- catch (error) {
480
- // The EXCL open created the file; don't leave a torn one behind.
481
- await sftpCloseHandle(this.sftp, handle).catch(() => undefined);
482
- await sftpUnlink(this.sftp, resolved).catch(() => undefined);
483
- throw error;
484
- }
485
- await sftpCloseHandle(this.sftp, handle);
486
- }
487
- else {
488
- // Check before the upload — a stale file shouldn't cost the whole transfer.
489
- await this.assertUnchanged(path, options, encoding);
490
- const tmp = posix.join(posix.dirname(resolved), `.${posix.basename(resolved)}.tmp-${randomBytes(6).toString("hex")}`);
491
- try {
492
- await sftpWriteFile(this.sftp, tmp, buf);
493
- const target = await sftpStat(this.sftp, resolved).catch(() => undefined);
494
- if (target !== undefined)
495
- await sftpSetstat(this.sftp, tmp, { mode: target.mode & 0o7777 });
496
- await this.assertUnchanged(path, options, encoding); // re-check right before the swap
497
- await sftpAtomicRename(this.sftp, tmp, resolved);
498
- }
499
- catch (error) {
500
- await sftpUnlink(this.sftp, tmp).catch(() => undefined);
501
- throw error;
502
- }
503
- }
504
- const after = await this.fileInfo(path); // still inside the lock — the version is THIS write's
505
- return { bytesWritten: buf.byteLength, version: fileVersionFromInfo(after) };
506
- });
507
- }
508
474
  /** SFTP has a native canonicalizer — exact, no readlink dependency. */
509
475
  async realpath(path) {
510
476
  return await sftpRealpath(this.sftp, this.resolvePath(path));
@@ -521,7 +487,7 @@ export class SshMachine extends BaseMachine {
521
487
  if (kind === "dir")
522
488
  continue;
523
489
  // `mkdir -p` tolerates existing DIRECTORIES only — a file occupant anywhere on
524
- // the way (final component included) is EEXIST, matching LocalMachine/Node.
490
+ // the way (final component included) is EEXIST, matching LocalEnvironment/Node.
525
491
  if (kind !== undefined)
526
492
  throw codedError(`${current} already exists and is not a directory`, "EEXIST");
527
493
  try {
@@ -550,8 +516,11 @@ export class SshMachine extends BaseMachine {
550
516
  // Layer proxy forwarding under the caller's overrides (caller wins on conflict).
551
517
  const merged = { ...this.injectedEnv, ...(env ?? {}) };
552
518
  const command = buildSshExecCommand(argv, this.cwd, Object.keys(merged).length > 0 ? merged : undefined);
553
- const channel = await clientExec(this.client, command);
554
- return new SshProcess(channel);
519
+ // A Windows server's shell has no process groups (or `sh`) to report — signal the channel.
520
+ if (this.osInfo.osKind === "Windows")
521
+ return new SshProcess(await clientExec(this.client, command));
522
+ const channel = await clientExec(this.client, SSH_PGID_REPORT + command);
523
+ return new SshProcess(channel, (side) => execForExitCode(this.client, side));
555
524
  }
556
525
  close() {
557
526
  this.sftp.end();
@@ -562,15 +531,15 @@ export class SshMachine extends BaseMachine {
562
531
  }
563
532
  }
564
533
  /*
565
- * No `sshMachineFactory` here on purpose. Its only job would be closing the connection on
534
+ * No `sshEnvironmentFactory` here on purpose. Its only job would be closing the connection on
566
535
  * session close — the lifecycle management that now belongs to whoever opened it (see
567
- * `MachineFactory`). A host wires SSH in the same way it wires a sandbox:
536
+ * `EnvironmentFactory`). A host wires SSH in the same way it wires a sandbox:
568
537
  *
569
- * const machine = await SshMachine.create(options);
570
- * const harness = new Harness({ machine });
571
- * // ...and calls machine.close() on its own terms.
538
+ * const environment = await SshEnvironment.create(options);
539
+ * const harness = new Harness({ environment });
540
+ * // ...and calls environment.close() on its own terms.
572
541
  *
573
542
  * That also fixes what the factory form got wrong: it opened a NEW connection per session,
574
543
  * so several sessions on one host meant several connections, each dying with its own session.
575
544
  */
576
- //# sourceMappingURL=machine-ssh.js.map
545
+ //# sourceMappingURL=environment-ssh.js.map