@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
package/workspace.ts ADDED
@@ -0,0 +1,181 @@
1
+ // File-and-command targets are independent of computer connection and sandbox
2
+ // provisioning. A connector only reaches an explicitly selected computer.
3
+ import { sleep as nap } from '@yaks/fp'
4
+ import type { Proc } from './mod.ts'
5
+
6
+ /** Commands and files in one filesystem; durable ids are process entity ids. */
7
+ export type Workspace = {
8
+ /** starts a command line, run by bash, and answers its id */
9
+ start(
10
+ command: string,
11
+ cwd?: string,
12
+ call?: string,
13
+ session?: string,
14
+ ): Promise<string>
15
+ /** the process a durable call started, where this machine can recover one */
16
+ receipt?: (call: string) => Promise<string | undefined>
17
+ /** the process by that id, or null when the machine has none */
18
+ look(id: string): Promise<Proc | null>
19
+ /** the last `n` lines it printed */
20
+ tail(id: string, n: number): Promise<string[]>
21
+ /** what it printed from byte `from` on, as far as it has printed; empty
22
+ * for an id the machine does not know */
23
+ output?: (id: string, from: number) => Promise<Uint8Array>
24
+ /** asks it to end */
25
+ kill(id: string, signal: 'SIGTERM' | 'SIGKILL'): Promise<void>
26
+ read(path: string): Promise<string>
27
+ /** what each path names, its links followed, in the order asked; a read,
28
+ * answered without starting a command */
29
+ stat(paths: string[]): Promise<Stat[]>
30
+ /** replaces what the path held, making its directory where it has none */
31
+ write(path: string, content: string): Promise<void>
32
+ writeBytes?: (path: string, bytes: Uint8Array) => Promise<void>
33
+ /** how soon a waiting call first looks again (ms, default 100); later
34
+ * looks come further apart, see `settle` */
35
+ poll?: number
36
+ }
37
+
38
+ /** What a path names once its links are followed, and its canonical path
39
+ * (every link resolved) wherever it names something: `dangling` is a link to
40
+ * nothing, and `missing` is no entry at all, or one this user cannot reach. */
41
+ export type Stat =
42
+ | { kind: 'missing' | 'dangling' }
43
+ | { kind: 'file' | 'directory' | 'other'; canonical: string }
44
+
45
+ /** Bytes from base64, whitespace and all. */
46
+ export let unbase64 = (text: string): Uint8Array =>
47
+ Uint8Array.from(atob(text.replaceAll(/\s/g, '')), (c) => c.charCodeAt(0))
48
+
49
+ /** UTF-8 text from base64, whitespace and all. */
50
+ export let decode = (text: string): string =>
51
+ new TextDecoder().decode(unbase64(text))
52
+
53
+ // One shell for every path, and no forks but for a link: `cd -P` resolves a
54
+ // directory's links, as `pwd -P` says, and `realpath` runs only for a path
55
+ // whose last part is itself a link. A line each: the kind, then the canonical
56
+ // path with `%` and newline escaped as a URI would.
57
+ let statScript = (paths: string[]) =>
58
+ `here=$PWD
59
+ for f in ${paths.map(quote).join(' ')}; do
60
+ k=missing c=
61
+ if test -e "$f"; then
62
+ if test -f "$f"; then k=file; elif test -d "$f"; then k=directory; else k=other; fi
63
+ if test -L "$f"; then c=$(realpath -e -- "$f")
64
+ elif test $k = directory; then cd -P -- "$f" 2>/dev/null && c=$PWD
65
+ else case $f in */*) d=\${f%/*};; *) d=.;; esac
66
+ cd -P -- "\${d:-/}" 2>/dev/null && c=\${PWD%/}/\${f##*/}; fi
67
+ test -n "$c" || c=$(realpath -e -- "$f")
68
+ cd -- "$here"; c=\${c//%/%25}; c=\${c//$'\\n'/%0A}
69
+ elif test -L "$f"; then k=dangling; fi
70
+ printf '%s %s\\n' "$k" "$c"
71
+ done`
72
+
73
+ /** `stat` for a computer that runs bash scripts, all the paths in one. */
74
+ export let shellStat =
75
+ (execute: (script: string) => Promise<string>) =>
76
+ async (paths: string[]): Promise<Stat[]> => {
77
+ if (!paths.length) return []
78
+ let lines = (await execute(statScript(paths))).replace(/\n$/, '')
79
+ .split('\n')
80
+ if (lines.length != paths.length) {
81
+ throw new Error('Invalid workspace stat response')
82
+ }
83
+ return lines.map((line): Stat => {
84
+ let at = line.indexOf(' ')
85
+ let kind = line.slice(0, at), canonical = line.slice(at + 1)
86
+ if (kind == 'missing' || kind == 'dangling') return { kind }
87
+ if (
88
+ (kind == 'file' || kind == 'directory' || kind == 'other') && canonical
89
+ ) return { kind, canonical: decodeURIComponent(canonical) }
90
+ throw new Error('Invalid workspace stat response')
91
+ })
92
+ }
93
+
94
+ /** How long `settle` waits and what it tells time by; a test gives a virtual
95
+ * clock. */
96
+ export type SettleOpts = {
97
+ /** the longest to wait (ms, default no limit) */
98
+ ms?: number
99
+ /** ends the wait, never the command */
100
+ signal?: AbortSignal
101
+ now?: () => number
102
+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>
103
+ }
104
+
105
+ /** The process once it has ended, `ms` has passed or `signal` aborted,
106
+ * whichever is first; null for an id the machine does not know. Like checking
107
+ * a kettle, it looks often at first and then less: the first gap is the
108
+ * machine's `poll`, each next one half again as long, up to two seconds. A
109
+ * short command answers within a fraction of a second; a long wait costs a
110
+ * look every two seconds. */
111
+ export let settle = async (
112
+ m: Pick<Workspace, 'look' | 'poll'>,
113
+ id: string,
114
+ { ms = Infinity, signal, now = Date.now, sleep = nap }: SettleOpts = {},
115
+ ): Promise<Proc | null> => {
116
+ let end = now() + ms, gap = m.poll ?? 100
117
+ for (;;) {
118
+ let p = await m.look(id)
119
+ if (!p || p.exit || signal?.aborted || now() >= end) return p
120
+ await sleep(Math.max(0, Math.min(gap, end - now())), signal)
121
+ gap = Math.max(gap, Math.min(gap * 1.5, 2000))
122
+ }
123
+ }
124
+
125
+ /** The process once it has ended, or null for an id the machine does not
126
+ * know, handing `write` what it prints as it prints it: a terminal's view of
127
+ * a command on another computer. Each look reads what is new since the last;
128
+ * the first gap is the machine's `poll` and each quiet one half again as long,
129
+ * up to a second, so a run's last words come within a second of its end. An
130
+ * abort ends only the following, never the command. */
131
+ export let follow = async (
132
+ m: Pick<Workspace, 'look' | 'poll'> & Pick<Required<Workspace>, 'output'>,
133
+ id: string,
134
+ write: (bytes: Uint8Array) => void | Promise<void>,
135
+ { signal, sleep = nap }: Pick<SettleOpts, 'signal' | 'sleep'> = {},
136
+ ): Promise<Proc | null> => {
137
+ let at = 0, gap = m.poll ?? 100
138
+ for (;;) {
139
+ // Look first: what an ended process printed is all there by its exit.
140
+ let p = await m.look(id)
141
+ let bytes = await m.output(id, at)
142
+ if (bytes.length) {
143
+ at += bytes.length
144
+ await write(bytes)
145
+ gap = m.poll ?? 100
146
+ }
147
+ if (!p || p.exit || signal?.aborted) return p
148
+ await sleep(gap, signal)
149
+ gap = Math.min(gap * 1.5, 1000)
150
+ }
151
+ }
152
+
153
+ /** A concrete, immutable launch target. Paths are in the target filesystem. */
154
+ export type WorkspaceTarget = {
155
+ workspace: string
156
+ root: string
157
+ /** Absolute directory for receipts on the original filesystem. */
158
+ receipts: string
159
+ /** Each command's own systemd scope properties, such as `MemoryMax=6G`,
160
+ * where the computer runs systemd: the command past its cap is the one
161
+ * ended (@yaks/process/isolate `scope`). */
162
+ limits?: string[]
163
+ }
164
+
165
+ /** A computer transport executes a short control script, not a managed run.
166
+ * Failure must propagate; a remote failure never selects the local transport. */
167
+ export type ComputerTransport = {
168
+ execute(script: string): Promise<string>
169
+ /** how soon a wait on a process here first looks again (ms, default 100):
170
+ * a look is one control script, a local shell or a network round trip */
171
+ poll?: number
172
+ }
173
+
174
+ /** A configured connector reaches an existing computer, never provisions it. */
175
+ export type ComputerConnector = {
176
+ connect(address: string): Promise<ComputerTransport>
177
+ }
178
+
179
+ /** Quote one value for the POSIX shell. */
180
+ export let quote = (value: string): string =>
181
+ "'" + value.replaceAll("'", "'\\''") + "'"
package/workspaces.js ADDED
@@ -0,0 +1,38 @@
1
+ // Connect existing workspace records through explicitly supplied bindings.
2
+ // Sandbox adapters are injected by the host; this package never provisions.
3
+ import { Refused } from "@yaks/graph/errors";
4
+ import { computer } from "./connectors.js";
5
+ import { executionWorkspace } from "./execution.js";
6
+ /** Unknown placement and unconfigured sandbox backends refuse, never go local. */ export let workspaces = (g, bindings)=>({
7
+ connect: async (id)=>{
8
+ let row = (await g.get([
9
+ id
10
+ ]))[0];
11
+ let target = row?.workspace;
12
+ if (!target) throw new Refused('Not a workspace: ' + id);
13
+ if (row?.released) throw new Refused('Workspace has been released: ' + id);
14
+ let sandbox = target.sandbox ?? (row?.sandbox ? id : undefined);
15
+ if (sandbox) {
16
+ if (!bindings.sandbox) throw new Refused('No sandbox workspace binding');
17
+ return await bindings.sandbox(String(sandbox));
18
+ }
19
+ if (!target.machine) {
20
+ throw new Refused('Workspace computer placement is unknown: ' + id);
21
+ }
22
+ let machine = (await g.get([
23
+ String(target.machine)
24
+ ], [
25
+ 'machine'
26
+ ]))[0]?.machine;
27
+ let transport = await computer(machine?.address, bindings.connectors);
28
+ if (typeof target.root != 'string') {
29
+ throw new Refused('Workspace root is unknown: ' + id);
30
+ }
31
+ return executionWorkspace(g, transport, {
32
+ workspace: id,
33
+ root: target.root,
34
+ receipts: bindings.receipts
35
+ });
36
+ }
37
+ });
38
+ //# sourceMappingURL=workspaces.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workspaces.js","sources":["./workspaces.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,4EAA4E;AAC5E,SAAS,OAAO,kCAAuC;AAEvD,SAAS,QAAQ,0BAAyB;AAC1C,SAAS,kBAAkB,yBAAwB;AAUnD,gFAAgF,GAChF,OAAO,IAAI,aAAa,CACtB,GACA,WACe,CAAC;IAChB,SAAS,OAAO;MACd,IAAI,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC;QAAC;OAAG,CAAC,CAAC,CAAC,EAAE;MAChC,IAAI,SAAS,KAAK;MAClB,IAAI,CAAC,QAAQ,MAAM,IAAI,QAAQ,sBAAsB;MACrD,IAAI,KAAK,UAAU,MAAM,IAAI,QAAQ,kCAAkC;MACvE,IAAI,UAAU,OAAO,OAAO,IAAI,CAAC,KAAK,UAAU,KAAK,SAAS;MAC9D,IAAI,SAAS;QACX,IAAI,CAAC,SAAS,OAAO,EAAE,MAAM,IAAI,QAAQ;QACzC,OAAO,MAAM,SAAS,OAAO,CAAC,OAAO;MACvC;MACA,IAAI,CAAC,OAAO,OAAO,EAAE;QACnB,MAAM,IAAI,QAAQ,8CAA8C;MAClE;MACA,IAAI,UAAU,CAAC,MAAM,EAAE,GAAG,CAAC;QAAC,OAAO,OAAO,OAAO;OAAE,EAAE;QAAC;OAAU,CAAC,CAAC,CAAC,EAAE,EACjE;MACJ,IAAI,YAAY,MAAM,SACpB,SAAS,SACT,SAAS,UAAU;MAErB,IAAI,OAAO,OAAO,IAAI,IAAI,UAAU;QAClC,MAAM,IAAI,QAAQ,gCAAgC;MACpD;MACA,OAAO,mBAAmB,GAAG,WAAW;QACtC,WAAW;QACX,MAAM,OAAO,IAAI;QACjB,UAAU,SAAS,QAAQ;MAC7B;IACF;EACF,CAAC,EAAC"}
package/workspaces.ts ADDED
@@ -0,0 +1,49 @@
1
+ // Connect existing workspace records through explicitly supplied bindings.
2
+ // Sandbox adapters are injected by the host; this package never provisions.
3
+ import { Refused } from '@yaks/graph/errors'
4
+ import type { Comp, Graph } from 'jsr:@yaks/graph@0.2.36'
5
+ import { computer } from './connectors.js'
6
+ import { executionWorkspace } from './execution.js'
7
+ import type { ComputerConnector, Workspace } from './workspace.ts'
8
+ import type { Workspaces } from './targets.ts'
9
+
10
+ export type WorkspaceBindings = {
11
+ connectors: Record<string, ComputerConnector>
12
+ receipts: string
13
+ sandbox?: (id: string) => Promise<Workspace>
14
+ }
15
+
16
+ /** Unknown placement and unconfigured sandbox backends refuse, never go local. */
17
+ export let workspaces = (
18
+ g: Graph,
19
+ bindings: WorkspaceBindings,
20
+ ): Workspaces => ({
21
+ connect: async (id) => {
22
+ let row = (await g.get([id]))[0]
23
+ let target = row?.workspace as Comp | undefined
24
+ if (!target) throw new Refused('Not a workspace: ' + id)
25
+ if (row?.released) throw new Refused('Workspace has been released: ' + id)
26
+ let sandbox = target.sandbox ?? (row?.sandbox ? id : undefined)
27
+ if (sandbox) {
28
+ if (!bindings.sandbox) throw new Refused('No sandbox workspace binding')
29
+ return await bindings.sandbox(String(sandbox))
30
+ }
31
+ if (!target.machine) {
32
+ throw new Refused('Workspace computer placement is unknown: ' + id)
33
+ }
34
+ let machine = (await g.get([String(target.machine)], ['machine']))[0]
35
+ ?.machine as Comp | undefined
36
+ let transport = await computer(
37
+ machine?.address as string | undefined,
38
+ bindings.connectors,
39
+ )
40
+ if (typeof target.root != 'string') {
41
+ throw new Refused('Workspace root is unknown: ' + id)
42
+ }
43
+ return executionWorkspace(g, transport, {
44
+ workspace: id,
45
+ root: target.root,
46
+ receipts: bindings.receipts,
47
+ })
48
+ },
49
+ })