@yaks/machine 0.0.0-stage → 0.2.36

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 (71) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +243 -2
  3. package/_dist/comp.d.ts +5 -0
  4. package/_dist/comp.d.ts.map +1 -0
  5. package/_dist/connectors.d.ts +29 -0
  6. package/_dist/connectors.d.ts.map +1 -0
  7. package/_dist/effects.d.ts +5 -0
  8. package/_dist/effects.d.ts.map +1 -0
  9. package/_dist/execution.d.ts +6 -0
  10. package/_dist/execution.d.ts.map +1 -0
  11. package/_dist/graph.d.ts +4 -0
  12. package/_dist/graph.d.ts.map +1 -0
  13. package/_dist/mod.d.ts +12 -0
  14. package/_dist/mod.d.ts.map +1 -0
  15. package/_dist/recorded.d.ts +4 -0
  16. package/_dist/recorded.d.ts.map +1 -0
  17. package/_dist/room.d.ts +45 -0
  18. package/_dist/room.d.ts.map +1 -0
  19. package/_dist/targets.d.ts +27 -0
  20. package/_dist/targets.d.ts.map +1 -0
  21. package/_dist/tools.d.ts +51 -0
  22. package/_dist/tools.d.ts.map +1 -0
  23. package/_dist/vocab.d.ts +5 -0
  24. package/_dist/vocab.d.ts.map +1 -0
  25. package/_dist/workspace.d.ts +64 -0
  26. package/_dist/workspace.d.ts.map +1 -0
  27. package/_dist/workspaces.d.ts +10 -0
  28. package/_dist/workspaces.d.ts.map +1 -0
  29. package/comp.js +3 -0
  30. package/comp.js.map +1 -0
  31. package/comp.ts +3 -0
  32. package/connectors.js +149 -0
  33. package/connectors.js.map +1 -0
  34. package/connectors.ts +221 -0
  35. package/deno.json +1 -0
  36. package/effect-vocab.json +40 -0
  37. package/effects.js +71 -0
  38. package/effects.js.map +1 -0
  39. package/effects.ts +93 -0
  40. package/execution.js +239 -0
  41. package/execution.js.map +1 -0
  42. package/execution.ts +264 -0
  43. package/graph.js +70 -0
  44. package/graph.js.map +1 -0
  45. package/graph.ts +60 -0
  46. package/mod.js +5 -0
  47. package/mod.js.map +1 -0
  48. package/mod.ts +20 -0
  49. package/package.json +62 -4
  50. package/recorded.js +108 -0
  51. package/recorded.js.map +1 -0
  52. package/recorded.ts +74 -0
  53. package/room.js +160 -0
  54. package/room.js.map +1 -0
  55. package/room.ts +228 -0
  56. package/targets.js +127 -0
  57. package/targets.js.map +1 -0
  58. package/targets.ts +137 -0
  59. package/tools.js +346 -0
  60. package/tools.js.map +1 -0
  61. package/tools.ts +444 -0
  62. package/vocab.js +17 -0
  63. package/vocab.js.map +1 -0
  64. package/vocab.json +69 -0
  65. package/vocab.ts +13 -0
  66. package/workspace.js +79 -0
  67. package/workspace.js.map +1 -0
  68. package/workspace.ts +181 -0
  69. package/workspaces.js +38 -0
  70. package/workspaces.js.map +1 -0
  71. package/workspaces.ts +49 -0
@@ -0,0 +1,51 @@
1
+ import type { EffectAnswer } from "@yaks/effects/invocation";
2
+ import type { Bundle } from "@yaks/graph";
3
+ /** Structural tool interface, independent of a transcript runner. */ export type ToolContext = {
4
+ session: string;
5
+ call: Bundle;
6
+ entries: Bundle[];
7
+ signal?: AbortSignal;
8
+ };
9
+ export type Tool = {
10
+ name: string;
11
+ description: string;
12
+ parameters: Record<string, unknown>;
13
+ run: (args: Record<string, unknown>, ctx?: ToolContext) => Promise<string> | string;
14
+ recover?: (args: Record<string, unknown>, ctx: ToolContext) => Promise<string | undefined> | string | undefined;
15
+ /** A call to it is the model waiting: a transcript starts no turn for it
16
+ * while it runs (@yaks/session `PATIENCE`). */ waits?: boolean;
17
+ };
18
+ import type { Graph } from "@yaks/graph";
19
+ import { type Workspaces } from "./targets.js";
20
+ import type { Machine } from "./mod.js";
21
+ /** How the machine tools behave, all optional. */ export type MachineOpts = {
22
+ /** The durable invocation when a host calls outside a session runner. */ call?: string;
23
+ /** how long `shell` waits for its command before answering the process id
24
+ * instead (ms, default 5000); a `timeout` argument overrides it per call */ budget?: number;
25
+ /** how long `stop` gives SIGTERM before SIGKILL (ms, default 2000) */ grace?: number;
26
+ /** how many lines of output an answer carries (default all) */ lines?: number;
27
+ /** where every command starts, and what a relative file path is read from */ cwd?: (ctx?: ToolContext) => string | undefined | Promise<string | undefined>;
28
+ };
29
+ /** Whether a path names its own root.
30
+ *
31
+ * ```ts
32
+ * import { assert } from '@std/assert'
33
+ * assert(rooted('/etc/hosts') && rooted('C:\\tmp') && !rooted('src/lib.rs'))
34
+ * ```
35
+ */ export declare let rooted: (path: string) => boolean;
36
+ /** A machine tool without its machine: what a door lists before it has one
37
+ * to run it on. */ export type MachineTool = Omit<Tool, 'run'>;
38
+ /** The machine tools' declarations: `shell`, `wait`, `stop`, `read` and
39
+ * `write`. */ export declare let machineDeclared: (o?: MachineOpts) => MachineTool[];
40
+ /**
41
+ * The machine tools over a machine.
42
+ *
43
+ * A command that finishes within its timeout answers its code and output; one
44
+ * that does not answers its process id, still running, for `wait` and `stop`
45
+ * to name.
46
+ */ export declare let machineTools: (source: Machine | ((ctx?: ToolContext) => Promise<Machine>), o?: MachineOpts) => Tool[];
47
+ /** File and process operations over one workspace. */ export declare let machineOperations: (m: Machine, o?: MachineOpts) => Record<string, (args: Record<string, unknown>, ctx?: ToolContext) => Promise<EffectAnswer>>;
48
+ /** Recover the command identified by its invocation, without starting one. */ export declare let shellReceipt: (m: Machine, call?: string) => Promise<string | undefined>;
49
+ /** Bind tools to graph targets. Each call persists its concrete target before
50
+ * touching a filesystem. Recovery refuses an invocation without that target. */ export declare let workspaceTools: (g: Graph, workspaces: Workspaces, o?: MachineOpts) => Tool[];
51
+ //# sourceMappingURL=tools.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tools.d.ts","sources":["../tools.ts"],"names":[],"mappings":"AACA,cAAc,YAAY,wCAA6C;AACvE,cAAc,MAAM,2BAAgC;AAEpD,mEAAmE,GACnE,YAAY;EACV,SAAS,MAAM;EACf,MAAM;EACN,SAAS;EACT,SAAS;;AAEX,YAAY;EACV,MAAM,MAAM;EACZ,aAAa,MAAM;EACnB,Y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 import type { VocabDoc } from "@yaks/vocab";
2
+ /** The machine vocabulary. */ export declare let machineDoc: VocabDoc;
3
+ /** The package's description, from its manifest. */ export declare let description: string;
4
+ /** Every vocabulary document this package declares. */ export declare let docs: VocabDoc[];
5
+ //# sourceMappingURL=vocab.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vocab.d.ts","sources":["../vocab.ts"],"names":[],"mappings":"AAEA,cAAc,QAAQ,2BAAgC;AAKtD,4BAA4B,GAC5B,OAAO,YAAI,YAAY,SAA0B;AACjD,kDAAkD,GAClD,OAAO,YAAI,aAAa,MAAM,CAAuB;AACrD,qDAAqD,GACrD,OAAO,YAAI,MAAM,WAAiD"}
@@ -0,0 +1,64 @@
1
+ import type { Proc } from "./mod.js";
2
+ /** Commands and files in one filesystem; durable ids are process entity ids. */ export type Workspace = {
3
+ /** starts a command line, run by bash, and answers its id */ start(command: string, cwd?: string, call?: string, session?: string): Promise<string>;
4
+ /** the process a durable call started, where this machine can recover one */ receipt?: (call: string) => Promise<string | undefined>;
5
+ /** the process by that id, or null when the machine has none */ look(id: string): Promise<Proc | null>;
6
+ /** the last `n` lines it printed */ tail(id: string, n: number): Promise<string[]>;
7
+ /** what it printed from byte `from` on, as far as it has printed; empty
8
+ * for an id the machine does not know */ output?: (id: string, from: number) => Promise<Uint8Array>;
9
+ /** asks it to end */ kill(id: string, signal: 'SIGTERM' | 'SIGKILL'): Promise<void>;
10
+ read(path: string): Promise<string>;
11
+ /** what each path names, its links followed, in the order asked; a read,
12
+ * answered without starting a command */ stat(paths: string[]): Promise<Stat[]>;
13
+ /** replaces what the path held, making its directory where it has none */ write(path: string, content: string): Promise<void>;
14
+ writeBytes?: (path: string, bytes: Uint8Array) => Promise<void>;
15
+ /** how soon a waiting call first looks again (ms, default 100); later
16
+ * looks come further apart, see `settle` */ poll?: number;
17
+ };
18
+ /** What a path names once its links are followed, and its canonical path
19
+ * (every link resolved) wherever it names something: `dangling` is a link to
20
+ * nothing, and `missing` is no entry at all, or one this user cannot reach. */ export type Stat = {
21
+ kind: 'missing' | 'dangling';
22
+ } | {
23
+ kind: 'file' | 'directory' | 'other';
24
+ canonical: string;
25
+ };
26
+ /** `stat` for a computer that runs bash scripts, all the paths in one. */ export declare let shellStat: (execute: (script: string) => Promise<string>) => any;
27
+ /** How long `settle` waits and what it tells time by; a test gives a virtual
28
+ * clock. */ export type SettleOpts = {
29
+ /** the longest to wait (ms, default no limit) */ ms?: number;
30
+ /** ends the wait, never the command */ signal?: AbortSignal;
31
+ now?: () => number;
32
+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
33
+ };
34
+ /** The process once it has ended, `ms` has passed or `signal` aborted,
35
+ * whichever is first; null for an id the machine does not know. Like checking
36
+ * a kettle, it looks often at first and then less: the first gap is the
37
+ * machine's `poll`, each next one half again as long, up to two seconds. A
38
+ * short command answers within a fraction of a second; a long wait costs a
39
+ * look every two seconds. */ export declare let settle: (m: Pick<Workspace, 'look' | 'poll'>, id: string, _dts_1: never) => Promise<Proc | null>;
40
+ /** The process once it has ended, or null for an id the machine does not
41
+ * know, handing `write` what it prints as it prints it: a terminal's view of
42
+ * a command on another computer. Each look reads what is new since the last;
43
+ * the first gap is the machine's `poll` and each quiet one half again as long,
44
+ * up to a second, so a run's last words come within a second of its end. An
45
+ * abort ends only the following, never the command. */ export declare let follow: (m: Pick<Workspace, 'look' | 'poll'> & Pick<Required<Workspace>, 'output'>, id: string, write: (bytes: Uint8Array) => void | Promise<void>, _dts_2: never) => Promise<Proc | null>;
46
+ /** A concrete, immutable launch target. Paths are in the target filesystem. */ export type WorkspaceTarget = {
47
+ workspace: string;
48
+ root: string;
49
+ /** Absolute directory for receipts on the original filesystem. */ receipts: string;
50
+ /** Each command's own systemd scope properties, such as `MemoryMax=6G`,
51
+ * where the computer runs systemd: the command past its cap is the one
52
+ * ended (@yaks/process/isolate `scope`). */ limits?: string[];
53
+ };
54
+ /** A computer transport executes a short control script, not a managed run.
55
+ * Failure must propagate; a remote failure never selects the local transport. */ export type ComputerTransport = {
56
+ execute(script: string): Promise<string>;
57
+ /** how soon a wait on a process here first looks again (ms, default 100):
58
+ * a look is one control script, a local shell or a network round trip */ poll?: number;
59
+ };
60
+ /** A configured connector reaches an existing computer, never provisions it. */ export type ComputerConnector = {
61
+ connect(address: string): Promise<ComputerTransport>;
62
+ };
63
+ /** Quote one value for the POSIX shell. */ export declare let quote: (value: string) => string;
64
+ //# sourceMappingURL=workspace.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workspace.d.ts","sources":["../workspace.ts"],"names":[],"mappings":"AAGA,cAAc,IAAI,mBAAkB;AAEpC,8EAA8E,GAC9E,YAAY;EACV,2DAA2D,GAC3D,MACE,SAAS,MAAM,EACf,MAAM,MAAM,EACZ,OAAO,MAAM,EACb,UAAU,MAAM,GACf,QAAQ,MAAM;EACjB,2EAA2E,GAC3E,WAAW,MAAM,MAAM,KAAK,QAAQ,MAAM,GAAG,SAAS;EACtD,8DAA8D,GAC9D,KAAK,IAAI,MAAM,GAAG,QAAQ,OAAO,IAAI;EACrC,kCAAkC,GAClC,KAAK,IAAI,MAAM,EAAE,GAAG,MAAM,GAAG,QAAQ,MAAM;EAC3C;yCACuC,GACvC,UAAU,IAAI,MAAM,EAAE,MAAM,MAAM,KAAK,QAAQ;EAC/C,mBAAmB,GACnB,KAAK,IAAI,MAAM,EAAE,QAAQ,YAAY,YAAY,QAAQ,IAAI;EAC7D,KAAK,MAAM,MAAM,GAAG,QAAQ,MAAM;EAClC;yCACuC,GACvC,KAAK,OAAO,MAAM,KAAK,QAAQ;EAC/B,wEAAwE,GACxE,MAAM,MAAM,MAAM,EAAE,SAAS,MAAM,GAAG,QAAQ,IAAI;EAClD,cAAc,MAAM,MAAM,EAAE,OAAO,eAAe,QAAQ,IAAI;EAC9D;4CAC0C,GAC1C,OAAO,MAAM;;AAGf;;6EAE6E,GAC7E,YAAY;EACN,MAAM,YAAY;;EAClB,MAAM,SAAS,cAAc;EAAS,WAAW,MAAM;;AA8B7D,wEAAwE,GACxE,OAAO,YAAI,YACR,UAAU,QAAQ,MAAM,KAAK,QAAQ,MAAM,UAiB3C;AAEH;UACU,GACV,YAAY;EACV,+CAA+C,GAC/C,KAAK,MAAM;EACX,qCAAqC,GACrC,SAAS;EACT,YAAY,MAAM;EAClB,SAAS,IAAI,MAAM,EAAE,SAAS,gBAAgB,QAAQ,IAAI;;AAG5D;;;;;2BAK2B,GAC3B,OAAO,YAAI,SACT,GAAG,KAAK,WAAW,SAAS,SAC5B,IAAI,MAAM,EACV,kBACC,QAAQ,OAAO,IAAI,EAQrB;AAED;;;;;qDAKqD,GACrD,OAAO,YAAI,SACT,GAAG,KAAK,WAAW,SAAS,UAAU,KAAK,SAAS,YAAY,WAChE,IAAI,MAAM,EACV,QAAQ,OAAO,eAAe,IAAI,GAAG,QAAQ,IAAI,GACjD,kBACC,QAAQ,OAAO,IAAI,EAerB;AAED,6EAA6E,GAC7E,YAAY;EACV,WAAW,MAAM;EACjB,MAAM,MAAM;EACZ,gEAAgE,GAChE,UAAU,MAAM;EAChB;;4CAE0C,GAC1C,SAAS,MAAM;;AAGjB;+EAC+E,GAC/E,YAAY;EACV,QAAQ,QAAQ,MAAM,GAAG,QAAQ,MAAM;EACvC;yEACuE,GACvE,OAAO,MAAM;;AAGf,8EAA8E,GAC9E,YAAY;EACV,QAAQ,SAAS,MAAM,GAAG,QAAQ;;AAGpC,yCAAyC,GACzC,OAAO,YAAI,QAAS,OAAO,MAAM,KAAG,MAAM,CACE"}
@@ -0,0 +1,10 @@
1
+ import type { Graph } from "@yaks/graph";
2
+ import type { ComputerConnector, Workspace } from "./workspace.js";
3
+ import type { Workspaces } from "./targets.js";
4
+ export type WorkspaceBindings = {
5
+ connectors: Record<string, ComputerConnector>;
6
+ receipts: string;
7
+ sandbox?: (id: string) => Promise<Workspace>;
8
+ };
9
+ /** Unknown placement and unconfigured sandbox backends refuse, never go local. */ export declare let workspaces: (g: Graph, bindings: WorkspaceBindings) => Workspaces;
10
+ //# sourceMappingURL=workspaces.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workspaces.d.ts","sources":["../workspaces.ts"],"names":[],"mappings":"AAGA,cAAoB,KAAK,2BAAgC;AAGzD,cAAc,iBAAiB,EAAE,SAAS,yBAAwB;AAClE,cAAc,UAAU,uBAAsB;AAE9C,YAAY;EACV,YAAY,OAAO,MAAM,EAAE;EAC3B,UAAU,MAAM;EAChB,WAAW,IAAI,MAAM,KAAK,QAAQ;;AAGpC,gFAAgF,GAChF,OAAO,YAAI,aACT,GAAG,OACH,UAAU,sBACT,WA6BD"}
package/comp.js ADDED
@@ -0,0 +1,3 @@
1
+ // An actual computer, reached through an explicitly configured connector.
2
+ export let MACHINE = 'machine';
3
+ //# sourceMappingURL=comp.js.map
package/comp.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"comp.js","sources":["./comp.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,OAAO,IAAI,UAAU,UAAS"}
package/comp.ts ADDED
@@ -0,0 +1,3 @@
1
+ // An actual computer, reached through an explicitly configured connector.
2
+ export let MACHINE = 'machine'
3
+ export type MachineRecord = { address?: string }
package/connectors.js ADDED
@@ -0,0 +1,149 @@
1
+ import { command as processCommand } from "@yaks/process/command";
2
+ // Explicit computer transports. Scripts cross only the configured connection;
3
+ // connector failures never fall back to the graph server's filesystem.
4
+ import { Refused } from "@yaks/graph/errors";
5
+ import { quote } from "./workspace.js";
6
+ /** Run a bounded control command; managed user commands are detached elsewhere. */ export let control = async (command, args, input)=>{
7
+ let child = processCommand(command, {
8
+ args,
9
+ stdin: 'piped',
10
+ stdout: 'piped',
11
+ stderr: 'piped'
12
+ }).spawn();
13
+ let writer = child.stdin.getWriter();
14
+ await writer.write(new TextEncoder().encode(input));
15
+ await writer.close();
16
+ let result = await child.output();
17
+ if (!result.success) {
18
+ throw new Error(`Computer control failed (${result.code}): ${new TextDecoder().decode(result.stderr)}`);
19
+ }
20
+ return new TextDecoder().decode(result.stdout);
21
+ };
22
+ /** Reach this computer only when explicitly addressed as local://. */ export let localConnector = (run = control)=>({
23
+ connect: (address)=>{
24
+ if (address != 'local://') {
25
+ throw new Error('Local connector requires local://');
26
+ }
27
+ // A look here is one local shell, so a short command's exit is seen
28
+ // within milliseconds rather than after a remote round trip's 100 ms.
29
+ return Promise.resolve({
30
+ execute: (script)=>run('bash', [
31
+ '-s'
32
+ ], script),
33
+ poll: 5
34
+ });
35
+ }
36
+ });
37
+ /** SSH uses the operator's known-host policy; it never disables verification.
38
+ * An identity file may be explicitly pinned without consulting a shared agent. */ export let sshConnector = (options = {})=>({
39
+ connect: (address)=>{
40
+ let url = new URL(address);
41
+ if (url.protocol != 'ssh:' || !url.hostname || url.password || url.search || url.hash || url.pathname && url.pathname != '/') {
42
+ throw new Error('SSH requires ssh://[user@]host[:port], not a directory or password');
43
+ }
44
+ let host = url.hostname;
45
+ let user = decodeURIComponent(url.username);
46
+ if (!/^[a-zA-Z0-9_.:-]+$/.test(host) || user && !/^[a-zA-Z0-9_.-]+$/.test(user)) throw new Error('Invalid SSH host or user');
47
+ let args = [
48
+ '-T',
49
+ '-o',
50
+ 'BatchMode=yes',
51
+ '-o',
52
+ 'ConnectTimeout=10',
53
+ '-o',
54
+ 'StrictHostKeyChecking=yes'
55
+ ];
56
+ if (options.knownHosts) {
57
+ args.push('-o', 'UserKnownHostsFile=' + options.knownHosts);
58
+ }
59
+ if (url.port) args.push('-p', url.port);
60
+ if (options.identity) {
61
+ args.push('-o', 'IdentityAgent=none', '-o', 'IdentitiesOnly=yes', '-i', options.identity);
62
+ }
63
+ args.push('--', user ? `${user}@${host}` : host, 'bash -s');
64
+ return Promise.resolve({
65
+ execute: (script)=>(options.run ?? control)('ssh', args, script)
66
+ });
67
+ }
68
+ });
69
+ /** HTTPS API transport with a fresh vault-resolved token on each request. */ export let pveRequest = (options)=>{
70
+ let base = new URL(options.endpoint);
71
+ if (base.protocol != 'https:' || base.username || base.password || base.search || base.hash) throw new Error('PVE endpoint must be credential-free HTTPS');
72
+ return async (method, path, values = {})=>{
73
+ if (!path.startsWith('/nodes/')) {
74
+ throw new Error('PVE control requires a node path');
75
+ }
76
+ let url = new URL(base);
77
+ url.pathname = '/api2/json' + path;
78
+ if (method == 'GET') {
79
+ for (let [key, value] of Object.entries(values)){
80
+ url.searchParams.set(key, String(value));
81
+ }
82
+ }
83
+ let result = await (options.fetch ?? fetch)(url, {
84
+ method,
85
+ redirect: 'error',
86
+ headers: {
87
+ Authorization: 'PVEAPIToken=' + await options.token(),
88
+ 'Content-Type': 'application/json'
89
+ },
90
+ ...method == 'POST' ? {
91
+ body: JSON.stringify(values)
92
+ } : {}
93
+ });
94
+ if (!result.ok) {
95
+ throw new Error(`PVE API refused control (${result.status})`);
96
+ }
97
+ let { data } = await result.json();
98
+ return data;
99
+ };
100
+ };
101
+ /** Reach a Linux QEMU guest through the PVE guest agent. LXC and the PVE host
102
+ * have no guest-agent exec door: reach those computers with SSH instead. */ export let pveConnector = (options)=>({
103
+ connect: (address)=>{
104
+ let match = /^pve:\/\/([a-zA-Z0-9_.-]+)\/qemu\/([1-9][0-9]*)$/.exec(address);
105
+ if (!match) {
106
+ throw new Error('PVE command target requires pve://node/qemu/VMID; use SSH for LXC or the PVE host');
107
+ }
108
+ let path = `/nodes/${match[1]}/qemu/${match[2]}/agent`;
109
+ return Promise.resolve({
110
+ execute: async (script)=>{
111
+ let result = await options.request('POST', path + '/exec', {
112
+ command: [
113
+ 'bash',
114
+ '-c',
115
+ script
116
+ ]
117
+ });
118
+ let pid = result.pid;
119
+ if (!Number.isSafeInteger(pid) || Number(pid) <= 0) {
120
+ throw new Error('PVE returned no control process handle');
121
+ }
122
+ for(let n = 0; n < (options.attempts ?? 100); n++){
123
+ let status = await options.request('GET', path + '/exec-status', {
124
+ pid
125
+ });
126
+ if (status.exited) {
127
+ if (status.exitcode !== 0 || status['out-truncated'] || status['err-truncated']) throw new Error('PVE control failed or returned truncated output');
128
+ return String(status['out-data'] ?? '');
129
+ }
130
+ await (options.pause ?? (()=>new Promise((r)=>setTimeout(r, 100))))();
131
+ }
132
+ throw new Error('PVE control timed out; reconnect to the original receipt, do not relaunch');
133
+ }
134
+ });
135
+ }
136
+ });
137
+ /** Select only a configured scheme, without an implicit local default. */ export let computer = async (address, configured)=>{
138
+ if (!address) throw new Refused('Computer placement/address is unknown');
139
+ let scheme = address.slice(0, address.indexOf(':'));
140
+ let connector = configured[scheme];
141
+ if (!connector) {
142
+ throw new Refused('Computer connector is not configured: ' + scheme);
143
+ }
144
+ return await connector.connect(address);
145
+ };
146
+ /** A diagnostic script that reads OS identity, not a directory-derived id.
147
+ * The caller reconciles this observation with a minted computer entity. */ export let computerIdentity = (transport)=>transport.execute(`cat /etc/machine-id || hostname`).then((s)=>s.trim());
148
+ /** Export the shell quoting used by connectors for downstream adapters. */ export { quote };
149
+ //# sourceMappingURL=connectors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connectors.js","sources":["./connectors.ts"],"names":[],"mappings":"AAAA,SAAS,WAAW,cAAc,qCAA0C;AAC5E,8EAA8E;AAC9E,uEAAuE;AACvE,SAAS,OAAO,kCAAuC;AAEvD,SAAS,KAAK,yBAAwB;AAStC,iFAAiF,GACjF,OAAO,IAAI,UAAyB,OAAO,SAAS,MAAM;EACxD,IAAI,QAAQ,eAAe,SAAS;IAClC;IACA,OAAO;IACP,QAAQ;IACR,QAAQ;EACV,GAAG,KAAK;EACR,IAAI,SAAS,MAAM,KAAK,CAAC,SAAS;EAClC,MAAM,OAAO,KAAK,CAAC,IAAI,cAAc,MAAM,CAAC;EAC5C,MAAM,OAAO,KAAK;EAClB,IAAI,SAAS,MAAM,MAAM,MAAM;EAC/B,IAAI,CAAC,OAAO,OAAO,EAAE;IACnB,MAAM,IAAI,MACR,CAAC,yBAAyB,EAAE,OAAO,IAAI,CAAC,GAAG,EACzC,IAAI,cAAc,MAAM,CAAC,OAAO,MAAM,GACtC;EAEN;EACA,OAAO,IAAI,c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yEACyE,GACzE,OAAO,IAAI,mBAAmB,CAAC,YAC7B,UAAU,OAAO,CAAC,CAAC,+BAA+B,CAAC,EAAE,IAAI,CAAC,CAAC,IAAM,EAAE,IAAI,IAAG;AAE5E,yEAAyE,GACzE,SAAS,KAAK,GAAE"}
package/connectors.ts ADDED
@@ -0,0 +1,221 @@
1
+ import { command as processCommand } from '@yaks/process/command'
2
+ // Explicit computer transports. Scripts cross only the configured connection;
3
+ // connector failures never fall back to the graph server's filesystem.
4
+ import { Refused } from '@yaks/graph/errors'
5
+ import type { ComputerConnector, ComputerTransport } from './workspace.js'
6
+ import { quote } from './workspace.js'
7
+
8
+ /** A checked short control command, also the injectable SSH test seam. */
9
+ export type ControlRunner = (
10
+ command: string,
11
+ args: string[],
12
+ input: string,
13
+ ) => Promise<string>
14
+
15
+ /** Run a bounded control command; managed user commands are detached elsewhere. */
16
+ export let control: ControlRunner = async (command, args, input) => {
17
+ let child = processCommand(command, {
18
+ args,
19
+ stdin: 'piped',
20
+ stdout: 'piped',
21
+ stderr: 'piped',
22
+ }).spawn()
23
+ let writer = child.stdin.getWriter()
24
+ await writer.write(new TextEncoder().encode(input))
25
+ await writer.close()
26
+ let result = await child.output()
27
+ if (!result.success) {
28
+ throw new Error(
29
+ `Computer control failed (${result.code}): ${
30
+ new TextDecoder().decode(result.stderr)
31
+ }`,
32
+ )
33
+ }
34
+ return new TextDecoder().decode(result.stdout)
35
+ }
36
+
37
+ /** Reach this computer only when explicitly addressed as local://. */
38
+ export let localConnector = (
39
+ run: ControlRunner = control,
40
+ ): ComputerConnector => ({
41
+ connect: (address) => {
42
+ if (address != 'local://') {
43
+ throw new Error('Local connector requires local://')
44
+ }
45
+ // A look here is one local shell, so a short command's exit is seen
46
+ // within milliseconds rather than after a remote round trip's 100 ms.
47
+ return Promise.resolve({
48
+ execute: (script: string) => run('bash', ['-s'], script),
49
+ poll: 5,
50
+ })
51
+ },
52
+ })
53
+
54
+ /** SSH uses the operator's known-host policy; it never disables verification.
55
+ * An identity file may be explicitly pinned without consulting a shared agent. */
56
+ export let sshConnector = (options: {
57
+ identity?: string
58
+ knownHosts?: string
59
+ run?: ControlRunner
60
+ } = {}): ComputerConnector => ({
61
+ connect: (address) => {
62
+ let url = new URL(address)
63
+ if (
64
+ url.protocol != 'ssh:' || !url.hostname || url.password || url.search ||
65
+ url.hash || (url.pathname && url.pathname != '/')
66
+ ) {
67
+ throw new Error(
68
+ 'SSH requires ssh://[user@]host[:port], not a directory or password',
69
+ )
70
+ }
71
+ let host = url.hostname
72
+ let user = decodeURIComponent(url.username)
73
+ if (
74
+ !/^[a-zA-Z0-9_.:-]+$/.test(host) ||
75
+ (user && !/^[a-zA-Z0-9_.-]+$/.test(user))
76
+ ) throw new Error('Invalid SSH host or user')
77
+ let args = [
78
+ '-T',
79
+ '-o',
80
+ 'BatchMode=yes',
81
+ '-o',
82
+ 'ConnectTimeout=10',
83
+ '-o',
84
+ 'StrictHostKeyChecking=yes',
85
+ ]
86
+ if (options.knownHosts) {
87
+ args.push('-o', 'UserKnownHostsFile=' + options.knownHosts)
88
+ }
89
+ if (url.port) args.push('-p', url.port)
90
+ if (options.identity) {
91
+ args.push(
92
+ '-o',
93
+ 'IdentityAgent=none',
94
+ '-o',
95
+ 'IdentitiesOnly=yes',
96
+ '-i',
97
+ options.identity,
98
+ )
99
+ }
100
+ args.push('--', user ? `${user}@${host}` : host, 'bash -s')
101
+ return Promise.resolve({
102
+ execute: (script: string) =>
103
+ (options.run ?? control)('ssh', args, script),
104
+ })
105
+ },
106
+ })
107
+
108
+ /** Request through a configured API binding. Authentication is supplied at
109
+ * invocation, never stored in an address or a process receipt. */
110
+ export type PveRequest = (
111
+ method: 'GET' | 'POST',
112
+ path: string,
113
+ values?: Record<string, unknown>,
114
+ ) => Promise<Record<string, unknown>>
115
+
116
+ /** HTTPS API transport with a fresh vault-resolved token on each request. */
117
+ export let pveRequest = (options: {
118
+ endpoint: string
119
+ token: () => Promise<string>
120
+ fetch?: typeof fetch
121
+ }): PveRequest => {
122
+ let base = new URL(options.endpoint)
123
+ if (
124
+ base.protocol != 'https:' || base.username || base.password ||
125
+ base.search || base.hash
126
+ ) throw new Error('PVE endpoint must be credential-free HTTPS')
127
+ return async (method, path, values = {}) => {
128
+ if (!path.startsWith('/nodes/')) {
129
+ throw new Error('PVE control requires a node path')
130
+ }
131
+ let url = new URL(base)
132
+ url.pathname = '/api2/json' + path
133
+ if (method == 'GET') {
134
+ for (let [key, value] of Object.entries(values)) {
135
+ url.searchParams.set(key, String(value))
136
+ }
137
+ }
138
+ let result = await (options.fetch ?? fetch)(url, {
139
+ method,
140
+ redirect: 'error',
141
+ headers: {
142
+ Authorization: 'PVEAPIToken=' + await options.token(),
143
+ 'Content-Type': 'application/json',
144
+ },
145
+ ...method == 'POST' ? { body: JSON.stringify(values) } : {},
146
+ })
147
+ if (!result.ok) {
148
+ throw new Error(`PVE API refused control (${result.status})`)
149
+ }
150
+ let { data } = await result.json() as { data: Record<string, unknown> }
151
+ return data
152
+ }
153
+ }
154
+
155
+ /** Reach a Linux QEMU guest through the PVE guest agent. LXC and the PVE host
156
+ * have no guest-agent exec door: reach those computers with SSH instead. */
157
+ export let pveConnector = (options: {
158
+ request: PveRequest
159
+ pause?: () => Promise<void>
160
+ attempts?: number
161
+ }): ComputerConnector => ({
162
+ connect: (address): Promise<ComputerTransport> => {
163
+ let match = /^pve:\/\/([a-zA-Z0-9_.-]+)\/qemu\/([1-9][0-9]*)$/.exec(address)
164
+ if (!match) {
165
+ throw new Error(
166
+ 'PVE command target requires pve://node/qemu/VMID; use SSH for LXC or the PVE host',
167
+ )
168
+ }
169
+ let path = `/nodes/${match[1]}/qemu/${match[2]}/agent`
170
+ return Promise.resolve({
171
+ execute: async (script: string) => {
172
+ let result = await options.request('POST', path + '/exec', {
173
+ command: ['bash', '-c', script],
174
+ })
175
+ let pid = result.pid
176
+ if (!Number.isSafeInteger(pid) || Number(pid) <= 0) {
177
+ throw new Error('PVE returned no control process handle')
178
+ }
179
+ for (let n = 0; n < (options.attempts ?? 100); n++) {
180
+ let status = await options.request('GET', path + '/exec-status', {
181
+ pid,
182
+ })
183
+ if (status.exited) {
184
+ if (
185
+ status.exitcode !== 0 || status['out-truncated'] ||
186
+ status['err-truncated']
187
+ ) throw new Error('PVE control failed or returned truncated output')
188
+ return String(status['out-data'] ?? '')
189
+ }
190
+ await (options.pause ??
191
+ (() => new Promise((r) => setTimeout(r, 100))))()
192
+ }
193
+ throw new Error(
194
+ 'PVE control timed out; reconnect to the original receipt, do not relaunch',
195
+ )
196
+ },
197
+ })
198
+ },
199
+ })
200
+
201
+ /** Select only a configured scheme, without an implicit local default. */
202
+ export let computer = async (
203
+ address: string | undefined,
204
+ configured: Record<string, ComputerConnector>,
205
+ ): Promise<ComputerTransport> => {
206
+ if (!address) throw new Refused('Computer placement/address is unknown')
207
+ let scheme = address.slice(0, address.indexOf(':'))
208
+ let connector = configured[scheme]
209
+ if (!connector) {
210
+ throw new Refused('Computer connector is not configured: ' + scheme)
211
+ }
212
+ return await connector.connect(address)
213
+ }
214
+
215
+ /** A diagnostic script that reads OS identity, not a directory-derived id.
216
+ * The caller reconciles this observation with a minted computer entity. */
217
+ export let computerIdentity = (transport: ComputerTransport): Promise<string> =>
218
+ transport.execute(`cat /etc/machine-id || hostname`).then((s) => s.trim())
219
+
220
+ /** Export the shell quoting used by connectors for downstream adapters. */
221
+ export { quote }
package/deno.json ADDED
@@ -0,0 +1 @@
1
+ {"publish":{"exclude":["**/*_test.ts"]},"name":"@yaks/machine","version":"0.2.36","license":"Apache-2.0","description":"Computers, explicit connection transports and durable file-and-command workspaces, separate from sandbox provisioning.","exports":{".":"./mod.ts","./vocab":"./vocab.ts","./connectors":"./connectors.ts","./execution":"./execution.ts","./recorded":"./recorded.ts","./effects":"./effects.ts","./tools":"./tools.ts","./targets":"./targets.ts","./workspaces":"./workspaces.ts","./graph":"./graph.ts","./room":"./room.ts"},"imports":{"@yaks/machine":"./mod.ts","@yaks/machine/vocab":"./vocab.ts","@yaks/machine/connectors":"./connectors.ts","@yaks/machine/execution":"./execution.ts","@yaks/machine/recorded":"./recorded.ts","@yaks/machine/effects":"./effects.ts","@yaks/machine/tools":"./tools.ts","@yaks/machine/targets":"./targets.ts","@yaks/machine/workspaces":"./workspaces.ts","@yaks/machine/graph":"./graph.ts","@yaks/machine/room":"./room.ts"}}
@@ -0,0 +1,40 @@
1
+ {
2
+ "title": "workspace effects",
3
+ "$defs": {
4
+ "shell": {
5
+ "effect": true,
6
+ "call": true,
7
+ "tries": 1,
8
+ "idempotent": false,
9
+ "description": "Start a command in a workspace and return its output and process receipt."
10
+ },
11
+ "wait": {
12
+ "effect": true,
13
+ "call": true,
14
+ "tries": 3,
15
+ "idempotent": true,
16
+ "description": "Read a workspace process output and exit when it ends or the wait times out."
17
+ },
18
+ "stop": {
19
+ "effect": true,
20
+ "call": true,
21
+ "tries": 3,
22
+ "idempotent": true,
23
+ "description": "Stop a workspace process and read its exit."
24
+ },
25
+ "read": {
26
+ "effect": true,
27
+ "call": true,
28
+ "tries": 3,
29
+ "idempotent": true,
30
+ "description": "Read a file or stat paths in a workspace."
31
+ },
32
+ "write": {
33
+ "effect": true,
34
+ "call": true,
35
+ "tries": 1,
36
+ "idempotent": false,
37
+ "description": "Replace a file in a workspace."
38
+ }
39
+ }
40
+ }