pi-suite 0.0.0-stage → 0.3.0

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 (220) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +100 -2
  3. package/README.zh-CN.md +101 -0
  4. package/package.json +63 -4
  5. package/skills/pi-suite-jobs/SKILL.md +76 -0
  6. package/skills/pi-suite-workflow/SKILL.md +114 -0
  7. package/src/agents/catalog.ts +80 -0
  8. package/src/agents/child.ts +79 -0
  9. package/src/agents/commands.ts +17 -0
  10. package/src/agents/defaults.ts +78 -0
  11. package/src/agents/history.ts +112 -0
  12. package/src/agents/index.ts +211 -0
  13. package/src/agents/manager.ts +438 -0
  14. package/src/agents/mentions/clone.ts +51 -0
  15. package/src/agents/mentions/grammar.ts +64 -0
  16. package/src/agents/mentions/index.ts +76 -0
  17. package/src/agents/mentions/provider.ts +79 -0
  18. package/src/agents/model-editor.ts +95 -0
  19. package/src/agents/models.ts +43 -0
  20. package/src/agents/output/schema.ts +101 -0
  21. package/src/agents/output/tool.ts +98 -0
  22. package/src/agents/parent.ts +13 -0
  23. package/src/agents/questions.ts +63 -0
  24. package/src/agents/records.ts +90 -0
  25. package/src/agents/registry.ts +20 -0
  26. package/src/agents/render.ts +85 -0
  27. package/src/agents/resources/context.ts +48 -0
  28. package/src/agents/resources/loader.ts +86 -0
  29. package/src/agents/resources/memory.ts +67 -0
  30. package/src/agents/resources/packages.ts +96 -0
  31. package/src/agents/resources/paths.ts +8 -0
  32. package/src/agents/resources/prompts.ts +11 -0
  33. package/src/agents/resources/scope.ts +147 -0
  34. package/src/agents/resources/selectors.ts +186 -0
  35. package/src/agents/retry.ts +20 -0
  36. package/src/agents/rpc/handlers.ts +62 -0
  37. package/src/agents/rpc/index.ts +73 -0
  38. package/src/agents/rpc/options.ts +44 -0
  39. package/src/agents/run-groups.ts +16 -0
  40. package/src/agents/runner.ts +131 -0
  41. package/src/agents/runtime.ts +40 -0
  42. package/src/agents/schedules/index.ts +136 -0
  43. package/src/agents/schedules/menu.ts +38 -0
  44. package/src/agents/schedules/parse.ts +42 -0
  45. package/src/agents/schedules/store.ts +78 -0
  46. package/src/agents/schema.ts +5 -0
  47. package/src/agents/session.ts +29 -0
  48. package/src/agents/tools.ts +177 -0
  49. package/src/agents/types.ts +87 -0
  50. package/src/agents/ui/index.ts +42 -0
  51. package/src/agents/ui/runs.ts +122 -0
  52. package/src/agents/ui/types.ts +91 -0
  53. package/src/agents/viewer-info.ts +36 -0
  54. package/src/agents/viewer.ts +160 -0
  55. package/src/agents/workflow/collisions.ts +124 -0
  56. package/src/agents/workflow/entry.ts +93 -0
  57. package/src/agents/workflow/host.ts +119 -0
  58. package/src/agents/workflow/index.ts +100 -0
  59. package/src/agents/workflow/journal.ts +147 -0
  60. package/src/agents/workflow/literal.ts +57 -0
  61. package/src/agents/workflow/manager.ts +169 -0
  62. package/src/agents/workflow/meta.ts +323 -0
  63. package/src/agents/workflow/progress/format.ts +184 -0
  64. package/src/agents/workflow/progress/index.ts +3 -0
  65. package/src/agents/workflow/progress/model.ts +224 -0
  66. package/src/agents/workflow/progress/types.ts +144 -0
  67. package/src/agents/workflow/render.ts +46 -0
  68. package/src/agents/workflow/runtime/helpers.ts +236 -0
  69. package/src/agents/workflow/runtime/index.ts +3 -0
  70. package/src/agents/workflow/runtime/run.ts +646 -0
  71. package/src/agents/workflow/runtime/types.ts +273 -0
  72. package/src/agents/workflow/saved.ts +74 -0
  73. package/src/agents/workflow/store.ts +23 -0
  74. package/src/agents/workflow/task.ts +277 -0
  75. package/src/agents/workflow/tool-description.ts +32 -0
  76. package/src/agents/workflow/tools.ts +66 -0
  77. package/src/agents/workflow/ui/menu.ts +144 -0
  78. package/src/agents/workflow/ui/progress.ts +91 -0
  79. package/src/agents/workflow/worker/bootstrap.ts +316 -0
  80. package/src/agents/workflow/worker/flow.ts +218 -0
  81. package/src/agents/workflow/worker/index.ts +7 -0
  82. package/src/agents/workflow/worker/scope.ts +215 -0
  83. package/src/ask/.gitkeep +0 -0
  84. package/src/ask/form.ts +67 -0
  85. package/src/ask/index.ts +73 -0
  86. package/src/ask/keys.ts +32 -0
  87. package/src/ask/layout.ts +78 -0
  88. package/src/ask/queue.ts +40 -0
  89. package/src/ask/render.ts +62 -0
  90. package/src/ask/result.ts +56 -0
  91. package/src/ask/schema.ts +67 -0
  92. package/src/ask/tool-render.ts +49 -0
  93. package/src/ask/view.ts +406 -0
  94. package/src/goal/.gitkeep +0 -0
  95. package/src/goal/activity.ts +50 -0
  96. package/src/goal/commands.ts +75 -0
  97. package/src/goal/context.ts +36 -0
  98. package/src/goal/index.ts +38 -0
  99. package/src/goal/manager.ts +386 -0
  100. package/src/goal/presentation.ts +15 -0
  101. package/src/goal/render.ts +36 -0
  102. package/src/goal/snapshot.ts +78 -0
  103. package/src/goal/state.ts +39 -0
  104. package/src/goal/store.ts +59 -0
  105. package/src/goal/tools.ts +59 -0
  106. package/src/goal/wait.ts +39 -0
  107. package/src/index.ts +20 -0
  108. package/src/jobs/backends/linux-tree.ts +87 -0
  109. package/src/jobs/backends/pipe.ts +74 -0
  110. package/src/jobs/backends/process.ts +79 -0
  111. package/src/jobs/backends/pty-job.ts +45 -0
  112. package/src/jobs/backends/pty.ts +502 -0
  113. package/src/jobs/backends/windows-tree.ts +289 -0
  114. package/src/jobs/commands.ts +7 -0
  115. package/src/jobs/control.ts +13 -0
  116. package/src/jobs/index.ts +331 -0
  117. package/src/jobs/launch/config.ts +26 -0
  118. package/src/jobs/launch/name.ts +16 -0
  119. package/src/jobs/launch/presets.ts +61 -0
  120. package/src/jobs/log-viewer.ts +147 -0
  121. package/src/jobs/manager.ts +507 -0
  122. package/src/jobs/monitors/compile.ts +101 -0
  123. package/src/jobs/monitors/hands-free.ts +108 -0
  124. package/src/jobs/monitors/runtime.ts +165 -0
  125. package/src/jobs/output.ts +54 -0
  126. package/src/jobs/query.ts +62 -0
  127. package/src/jobs/render.ts +103 -0
  128. package/src/jobs/runtime.ts +89 -0
  129. package/src/jobs/state.ts +25 -0
  130. package/src/jobs/store.ts +168 -0
  131. package/src/jobs/terminal/keys.ts +292 -0
  132. package/src/jobs/terminal/protocol.ts +37 -0
  133. package/src/jobs/terminal/read.ts +131 -0
  134. package/src/jobs/terminal/render.ts +70 -0
  135. package/src/jobs/terminal/screen.ts +92 -0
  136. package/src/jobs/terminal/session.ts +100 -0
  137. package/src/jobs/terminal/shell.ts +22 -0
  138. package/src/jobs/terminal/snapshot.ts +8 -0
  139. package/src/jobs/terminal/visible-text.ts +53 -0
  140. package/src/jobs/tools.ts +203 -0
  141. package/src/jobs/types.ts +60 -0
  142. package/src/jobs/viewer/component.ts +209 -0
  143. package/src/jobs/viewer/metadata.ts +9 -0
  144. package/src/jobs/viewer.ts +149 -0
  145. package/src/jobs/workspace.ts +31 -0
  146. package/src/runtime/.gitkeep +0 -0
  147. package/src/runtime/binding.ts +26 -0
  148. package/src/runtime/cli-prompt.ts +24 -0
  149. package/src/runtime/clipboard.ts +16 -0
  150. package/src/runtime/config-edit.ts +31 -0
  151. package/src/runtime/config-fields.ts +65 -0
  152. package/src/runtime/config.ts +111 -0
  153. package/src/runtime/errors.ts +11 -0
  154. package/src/runtime/json-store.ts +156 -0
  155. package/src/runtime/notification-render.ts +35 -0
  156. package/src/runtime/notifications.ts +98 -0
  157. package/src/runtime/owner.ts +54 -0
  158. package/src/runtime/read.ts +200 -0
  159. package/src/runtime/renderers.ts +50 -0
  160. package/src/runtime/responses/index.ts +108 -0
  161. package/src/runtime/responses/payload.ts +78 -0
  162. package/src/runtime/settings/index.ts +24 -0
  163. package/src/runtime/settings/view.ts +84 -0
  164. package/src/runtime/suite.ts +192 -0
  165. package/src/runtime/text.ts +6 -0
  166. package/src/runtime/tools.ts +131 -0
  167. package/src/runtime/wait-render.ts +33 -0
  168. package/src/runtime/wait.ts +134 -0
  169. package/src/tasks/commands.ts +41 -0
  170. package/src/tasks/index.ts +305 -0
  171. package/src/tasks/model.ts +152 -0
  172. package/src/tasks/presentation.ts +40 -0
  173. package/src/tasks/query.ts +38 -0
  174. package/src/tasks/render.ts +54 -0
  175. package/src/tasks/schema.ts +25 -0
  176. package/src/tasks/store.ts +164 -0
  177. package/src/tasks/tools.ts +69 -0
  178. package/src/tasks/types.ts +61 -0
  179. package/src/tasks/viewer.ts +68 -0
  180. package/src/ui/.gitkeep +0 -0
  181. package/src/ui/actions.ts +50 -0
  182. package/src/ui/browser-chrome.ts +175 -0
  183. package/src/ui/browser.ts +292 -0
  184. package/src/ui/details.ts +111 -0
  185. package/src/ui/dock/line.ts +14 -0
  186. package/src/ui/dock/rows.ts +78 -0
  187. package/src/ui/dock.ts +224 -0
  188. package/src/ui/format.ts +25 -0
  189. package/src/ui/frame.ts +8 -0
  190. package/src/ui/inline-input.ts +98 -0
  191. package/src/ui/reading.ts +105 -0
  192. package/src/ui/rendering/builtin-command.ts +34 -0
  193. package/src/ui/rendering/command.ts +60 -0
  194. package/src/ui/rendering/read-page.ts +15 -0
  195. package/src/ui/rendering/shell/bash.ts +281 -0
  196. package/src/ui/rendering/shell/index.ts +24 -0
  197. package/src/ui/rendering/shell/powershell.ts +155 -0
  198. package/src/ui/rendering/shell/spans.ts +28 -0
  199. package/src/ui/scroll.ts +111 -0
  200. package/src/ui/select.ts +67 -0
  201. package/src/ui/status.ts +67 -0
  202. package/src/ui/structured-details.ts +41 -0
  203. package/src/ui/terminal.ts +137 -0
  204. package/src/ui/ticker.ts +18 -0
  205. package/src/ui/tool-render.ts +152 -0
  206. package/src/ui/transcript.ts +140 -0
  207. package/src/ui/viewer/agent-information.ts +34 -0
  208. package/src/ui/viewer/editor.ts +18 -0
  209. package/src/ui/viewer/navigation.ts +25 -0
  210. package/themes/oh-my-pi.json +95 -0
  211. package/third-party/UPSTREAM.md +88 -0
  212. package/third-party/licenses/.gitkeep +0 -0
  213. package/third-party/licenses/oh-my-pi.txt +23 -0
  214. package/third-party/licenses/pi-ask-user.txt +21 -0
  215. package/third-party/licenses/pi-background-jobs.txt +21 -0
  216. package/third-party/licenses/pi-goal.txt +21 -0
  217. package/third-party/licenses/pi-interactive-shell.txt +25 -0
  218. package/third-party/licenses/pi-subagents.txt +21 -0
  219. package/third-party/licenses/pi-tasks.txt +21 -0
  220. package/third-party/sources.json +111 -0
@@ -0,0 +1,168 @@
1
+ // Adapted from pi-background-jobs 0.1.3 src/store.ts (MIT, third-party/licenses/pi-background-jobs.txt).
2
+ // Layout: <agentDir>/pi-suite/jobs/<workspaceHash>/<jobId>/{job.json,stdout.log,stderr.log,output.log,input.jsonl,events.jsonl}.
3
+ // A single job.json replaces meta/result: every write is an atomic rename, so a reader never
4
+ // sees a partial record. Log reading lives in read.ts; this module owns paths and history.
5
+ import { lstatSync, realpathSync, mkdirSync, writeFileSync, renameSync, unlinkSync, existsSync } from 'node:fs';
6
+ import { readdir, readFile, writeFile, rename, rm, stat, unlink, appendFile } from 'node:fs/promises';
7
+ import { join, relative, sep, isAbsolute } from 'node:path';
8
+ import { randomBytes, randomUUID } from 'node:crypto';
9
+ import { isTerminal } from './state.ts';
10
+ import { ToolError } from '../runtime/errors.ts';
11
+ import { SNAPSHOT_BYTES, SNAPSHOT_SCROLLBACK, type TerminalSnapshot } from './terminal/snapshot.ts';
12
+ import type { JobSummary, Workspace, Stream, InputRecord } from './types.ts';
13
+
14
+ const JOB_ID = /^job_[a-f0-9]{8}$/;
15
+ const HASH = /^[a-f0-9]{64}$/;
16
+ const STATES = ['starting', 'running', 'stopping', 'completed', 'failed', 'stopped', 'timed_out'];
17
+ const CLEANUP = ['not_required', 'pending', 'managed_scope_confirmed', 'unconfirmed'];
18
+ function contained(root: string, path: string): boolean {
19
+ const rel = relative(root, path);
20
+ return rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
21
+ }
22
+ export const LOG_FILES: Record<Stream, string> = { stdout: 'stdout.log', stderr: 'stderr.log', output: 'output.log', input: 'input.jsonl', events: 'events.jsonl' };
23
+
24
+ export class JobStore {
25
+ private base: string;
26
+ readonly root: string;
27
+ constructor(agentDir: string) {
28
+ this.base = realpathSync(agentDir);
29
+ this.root = join(this.base, 'pi-suite', 'jobs');
30
+ }
31
+ // Also used during synchronous process exit. Reject links at every owned level.
32
+ private secure(path: string, createDirs = false): void {
33
+ if (!contained(this.root, path)) throw new ToolError('UNSAFE_PATH', 'Job path leaves managed directory');
34
+ let current = this.base;
35
+ for (const piece of relative(this.base, path).split(sep).filter(Boolean)) {
36
+ current = join(current, piece);
37
+ try {
38
+ if (lstatSync(current).isSymbolicLink() || !contained(this.base, realpathSync(current))) throw new ToolError('UNSAFE_PATH', 'Managed path redirected by a link');
39
+ } catch (error) {
40
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
41
+ if (createDirs) mkdirSync(current, { mode: 0o700 });
42
+ else break;
43
+ }
44
+ }
45
+ }
46
+ directory(job: Pick<JobSummary, 'id' | 'workspace'>): string {
47
+ if (!JOB_ID.test(job.id) || !HASH.test(job.workspace.hash)) throw new ToolError('UNSAFE_PATH', 'Invalid internal job identity');
48
+ const dir = join(this.root, job.workspace.hash, job.id);
49
+ this.secure(dir);
50
+ return dir;
51
+ }
52
+ /** Checked path of one log; callers open it themselves so streams stay in one place. */
53
+ logPath(job: Pick<JobSummary, 'id' | 'workspace'>, stream: Stream): string {
54
+ const path = join(this.directory(job), LOG_FILES[stream]);
55
+ this.secure(path);
56
+ return path;
57
+ }
58
+ /** Allocate an unused short ID and its directory; collisions are retried, never reused. */
59
+ allocate(workspace: Workspace): string {
60
+ for (;;) {
61
+ const id = `job_${randomBytes(4).toString('hex')}`;
62
+ const dir = join(this.root, workspace.hash, id);
63
+ this.secure(dir);
64
+ if (existsSync(dir)) continue;
65
+ this.secure(dir, true);
66
+ return id;
67
+ }
68
+ }
69
+ async create(job: JobSummary): Promise<void> {
70
+ const streams: Stream[] = [...job.mode === 'pty' ? ['output', 'input'] as const : ['stdout', 'stderr', 'input'] as const, ...job.monitor ? ['events'] as const : []];
71
+ try {
72
+ for (const stream of streams) await writeFile(this.logPath(job, stream), '', { flag: 'wx', mode: 0o600 });
73
+ await this.save(job);
74
+ } catch (error) { throw new ToolError('STORAGE_ERROR', String(error), job.id); }
75
+ }
76
+ async save(job: JobSummary): Promise<void> {
77
+ const dir = this.directory(job), dest = join(dir, 'job.json'), temp = join(dir, `.${randomUUID()}.tmp`);
78
+ this.secure(dest);
79
+ try {
80
+ await writeFile(temp, JSON.stringify(job), { flag: 'wx', mode: 0o600 });
81
+ await rename(temp, dest);
82
+ } catch (error) { throw new ToolError('STORAGE_ERROR', String(error), job.id); }
83
+ finally { await unlink(temp).catch(() => {}); }
84
+ }
85
+ saveSync(job: JobSummary): void {
86
+ const dir = this.directory(job), dest = join(dir, 'job.json'), temp = join(dir, `.${randomUUID()}.tmp`);
87
+ this.secure(dest);
88
+ try { writeFileSync(temp, JSON.stringify(job), { flag: 'wx', mode: 0o600 }); renameSync(temp, dest); }
89
+ catch (error) { throw new ToolError('STORAGE_ERROR', String(error), job.id); }
90
+ finally { try { unlinkSync(temp); } catch {} }
91
+ }
92
+ /** Settlement-only atomic screen save. Removal of the job directory includes its snapshot. */
93
+ async saveTerminalSnapshot(job: JobSummary, snapshot: TerminalSnapshot): Promise<void> {
94
+ const dir = this.directory(job), dest = join(dir, 'terminal.json'), temp = join(dir, `.${randomUUID()}.tmp`);
95
+ this.secure(dest);
96
+ try {
97
+ await writeFile(temp, JSON.stringify(snapshot), {flag: 'wx', mode: 0o600});
98
+ await rename(temp, dest);
99
+ } catch (error) { throw new ToolError('STORAGE_ERROR', `terminal snapshot: ${String(error)}`, job.id); }
100
+ finally { await unlink(temp).catch(() => {}); }
101
+ }
102
+ async readTerminalSnapshot(job: JobSummary): Promise<TerminalSnapshot | undefined> {
103
+ if (!job.terminalSnapshot) return undefined;
104
+ const path = join(this.directory(job), 'terminal.json'); this.secure(path);
105
+ const size = (await stat(path)).size;
106
+ if (size > SNAPSHOT_BYTES * 2) throw new ToolError('CORRUPT_HISTORY', 'Terminal snapshot exceeds storage limit', job.id);
107
+ const snapshot = JSON.parse(await readFile(path, 'utf8')) as TerminalSnapshot;
108
+ if (snapshot?.version !== 1 || typeof snapshot.data !== 'string' || Buffer.byteLength(snapshot.data) > SNAPSHOT_BYTES ||
109
+ !Number.isInteger(snapshot.cols) || snapshot.cols < 1 || !Number.isInteger(snapshot.rows) || snapshot.rows < 1 ||
110
+ !Number.isInteger(snapshot.scrollback) || snapshot.scrollback < 0 || snapshot.scrollback > SNAPSHOT_SCROLLBACK ||
111
+ !Number.isInteger(snapshot.cursor?.x) || !Number.isInteger(snapshot.cursor?.y) || typeof snapshot.cursor?.visible !== 'boolean' ||
112
+ typeof snapshot.alternate !== 'boolean') throw new ToolError('CORRUPT_HISTORY', 'Invalid terminal snapshot', job.id);
113
+ return snapshot;
114
+ }
115
+ async appendInput(job: JobSummary, record: InputRecord): Promise<void> {
116
+ await appendFile(this.logPath(job, 'input'), JSON.stringify(record) + '\n', { mode: 0o600 });
117
+ }
118
+ /** Monitor events, one JSON line each; job_read renders them through the events stream. */
119
+ async appendEvent(job: JobSummary, event: object): Promise<void> {
120
+ await appendFile(this.logPath(job, 'events'), JSON.stringify(event) + '\n', { mode: 0o600 });
121
+ }
122
+ async logBytes(job: JobSummary): Promise<number> {
123
+ let bytes = 0;
124
+ for (const stream of job.mode === 'pty' ? ['output'] as const : ['stdout', 'stderr'] as const) bytes += (await stat(this.logPath(job, stream))).size;
125
+ return bytes;
126
+ }
127
+ async workspaceBytes(workspace: Workspace): Promise<number> {
128
+ if (!HASH.test(workspace.hash)) throw new ToolError('UNSAFE_PATH', 'Invalid workspace hash');
129
+ const count = async (path: string): Promise<number> => {
130
+ this.secure(path);
131
+ let info;
132
+ try { info = await stat(path); } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return 0; throw error; }
133
+ if (!info.isDirectory()) return info.size;
134
+ let bytes = 0;
135
+ for (const entry of await readdir(path)) bytes += await count(join(path, entry));
136
+ return bytes;
137
+ };
138
+ return count(join(this.root, workspace.hash));
139
+ }
140
+ /** History of one workspace. Corrupt records are reported per job instead of failing the list. */
141
+ async list(workspace: Workspace): Promise<{ jobs: JobSummary[]; errors: string[] }> {
142
+ if (!HASH.test(workspace.hash)) throw new ToolError('UNSAFE_PATH', 'Invalid workspace hash');
143
+ const root = join(this.root, workspace.hash); this.secure(root);
144
+ const jobs: JobSummary[] = [], errors: string[] = [];
145
+ let ids: string[];
146
+ try { ids = await readdir(root); }
147
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') errors.push(String(error)); return { jobs, errors }; }
148
+ for (const id of ids) {
149
+ try { jobs.push(await this.load(workspace, id)); }
150
+ catch (error) { errors.push(`${id}: ${String(error)}`.slice(0, 512)); }
151
+ }
152
+ return { jobs, errors };
153
+ }
154
+ async load(workspace: Workspace, id: string): Promise<JobSummary> {
155
+ const path = join(this.directory({ id, workspace }), 'job.json'); this.secure(path);
156
+ const job = JSON.parse(await readFile(path, 'utf8')) as JobSummary;
157
+ if (job?.schemaVersion !== 1 || job.id !== id || job.workspace?.hash !== workspace.hash || job.workspace.key !== workspace.key ||
158
+ !STATES.includes(job.state) || !['pipe', 'pty'].includes(job.mode) || typeof job.command !== 'string' ||
159
+ typeof job.ownerSessionId !== 'string' || !CLEANUP.includes(job.cleanup?.state)) throw new ToolError('CORRUPT_HISTORY', 'Unsupported or mismatched job record', id);
160
+ return job;
161
+ }
162
+ async remove(job: JobSummary): Promise<void> {
163
+ // Check disk state again; the caller's snapshot cannot authorize deleting live history.
164
+ const stored = await this.load(job.workspace, job.id);
165
+ if (!isTerminal(stored.state) || ['pending', 'unconfirmed'].includes(stored.cleanup.state)) throw new ToolError('JOB_OCCUPIED', 'Cannot delete an active or unconfirmed job', job.id);
166
+ await rm(this.directory(job), { recursive: true });
167
+ }
168
+ }
@@ -0,0 +1,292 @@
1
+ // Imported from pi-interactive-shell 0.18.0 key-encoding.ts (MIT, third-party/licenses/pi-interactive-shell.txt).
2
+ // pi-suite changes: the Jev semantic-action encoder is removed with semantic supervision; the
3
+ // unknown-key error names the job_write keys field.
4
+ /**
5
+ * Terminal key encoding utilities for translating named keys and modifiers
6
+ * into terminal escape sequences.
7
+ */
8
+
9
+ // Named key sequences (without modifiers)
10
+ const NAMED_KEYS: Record<string, string> = {
11
+ // Arrow keys
12
+ up: "\x1b[A",
13
+ down: "\x1b[B",
14
+ left: "\x1b[D",
15
+ right: "\x1b[C",
16
+
17
+ // Common keys
18
+ enter: "\r",
19
+ return: "\r",
20
+ escape: "\x1b",
21
+ esc: "\x1b",
22
+ tab: "\t",
23
+ space: " ",
24
+ backspace: "\x7f",
25
+ bspace: "\x7f", // tmux-style alias
26
+
27
+ // Editing keys
28
+ delete: "\x1b[3~",
29
+ del: "\x1b[3~",
30
+ dc: "\x1b[3~", // tmux-style alias
31
+ insert: "\x1b[2~",
32
+ ic: "\x1b[2~", // tmux-style alias
33
+
34
+ // Navigation
35
+ home: "\x1b[H",
36
+ end: "\x1b[F",
37
+ pageup: "\x1b[5~",
38
+ pgup: "\x1b[5~",
39
+ ppage: "\x1b[5~", // tmux-style alias
40
+ pagedown: "\x1b[6~",
41
+ pgdn: "\x1b[6~",
42
+ npage: "\x1b[6~", // tmux-style alias
43
+
44
+ // Shift+Tab (backtab)
45
+ btab: "\x1b[Z",
46
+
47
+ // Function keys
48
+ f1: "\x1bOP",
49
+ f2: "\x1bOQ",
50
+ f3: "\x1bOR",
51
+ f4: "\x1bOS",
52
+ f5: "\x1b[15~",
53
+ f6: "\x1b[17~",
54
+ f7: "\x1b[18~",
55
+ f8: "\x1b[19~",
56
+ f9: "\x1b[20~",
57
+ f10: "\x1b[21~",
58
+ f11: "\x1b[23~",
59
+ f12: "\x1b[24~",
60
+
61
+ // Keypad keys (application mode)
62
+ kp0: "\x1bOp",
63
+ kp1: "\x1bOq",
64
+ kp2: "\x1bOr",
65
+ kp3: "\x1bOs",
66
+ kp4: "\x1bOt",
67
+ kp5: "\x1bOu",
68
+ kp6: "\x1bOv",
69
+ kp7: "\x1bOw",
70
+ kp8: "\x1bOx",
71
+ kp9: "\x1bOy",
72
+ "kp/": "\x1bOo",
73
+ "kp*": "\x1bOj",
74
+ "kp-": "\x1bOm",
75
+ "kp+": "\x1bOk",
76
+ "kp.": "\x1bOn",
77
+ kpenter: "\x1bOM",
78
+ };
79
+
80
+ // Ctrl+key combinations (ctrl+a through ctrl+z, plus some special)
81
+ const CTRL_KEYS: Record<string, string> = {};
82
+ for (let i = 0; i < 26; i++) {
83
+ const char = String.fromCharCode(97 + i); // a-z
84
+ CTRL_KEYS[`ctrl+${char}`] = String.fromCharCode(i + 1);
85
+ }
86
+ // Special ctrl combinations
87
+ CTRL_KEYS["ctrl+["] = "\x1b"; // Same as Escape
88
+ CTRL_KEYS["ctrl+\\"] = "\x1c";
89
+ CTRL_KEYS["ctrl+]"] = "\x1d";
90
+ CTRL_KEYS["ctrl+^"] = "\x1e";
91
+ CTRL_KEYS["ctrl+_"] = "\x1f";
92
+ CTRL_KEYS["ctrl+?"] = "\x7f"; // Same as Backspace
93
+
94
+ // Alt+key sends ESC followed by the key
95
+ function altKey(char: string): string {
96
+ return `\x1b${char}`;
97
+ }
98
+
99
+ // Keys that support xterm modifier encoding (CSI sequences)
100
+ const MODIFIABLE_KEYS = new Set([
101
+ "up", "down", "left", "right", "home", "end",
102
+ "pageup", "pgup", "ppage", "pagedown", "pgdn", "npage",
103
+ "insert", "ic", "delete", "del", "dc",
104
+ ]);
105
+
106
+ // Calculate xterm modifier code: 1 + (shift?1:0) + (alt?2:0) + (ctrl?4:0)
107
+ function xtermModifier(shift: boolean, alt: boolean, ctrl: boolean): number {
108
+ let mod = 1;
109
+ if (shift) mod += 1;
110
+ if (alt) mod += 2;
111
+ if (ctrl) mod += 4;
112
+ return mod;
113
+ }
114
+
115
+ // Apply xterm modifier to CSI sequence: ESC[A -> ESC[1;modA
116
+ function applyXtermModifier(sequence: string, modifier: number): string | null {
117
+ // Arrow keys: ESC[A -> ESC[1;modA
118
+ const arrowMatch = sequence.match(/^\x1b\[([A-D])$/);
119
+ if (arrowMatch) {
120
+ return `\x1b[1;${modifier}${arrowMatch[1]}`;
121
+ }
122
+ // Numbered sequences: ESC[5~ -> ESC[5;mod~
123
+ const numMatch = sequence.match(/^\x1b\[(\d+)~$/);
124
+ if (numMatch) {
125
+ return `\x1b[${numMatch[1]};${modifier}~`;
126
+ }
127
+ // Home/End: ESC[H -> ESC[1;modH, ESC[F -> ESC[1;modF
128
+ const hfMatch = sequence.match(/^\x1b\[([HF])$/);
129
+ if (hfMatch) {
130
+ return `\x1b[1;${modifier}${hfMatch[1]}`;
131
+ }
132
+ return null;
133
+ }
134
+
135
+ // Bracketed paste mode sequences
136
+ const BRACKETED_PASTE_START = "\x1b[200~";
137
+ const BRACKETED_PASTE_END = "\x1b[201~";
138
+
139
+ function encodePaste(text: string, bracketed = true): string {
140
+ if (!bracketed) return text;
141
+ return `${BRACKETED_PASTE_START}${text}${BRACKETED_PASTE_END}`;
142
+ }
143
+
144
+ /** Parse a key token and return the escape sequence */
145
+ function encodeKeyToken(token: string): string {
146
+ const normalized = token.trim().toLowerCase();
147
+ if (!normalized) return "";
148
+
149
+ // Check for direct match in named keys
150
+ if (Object.hasOwn(NAMED_KEYS, normalized)) {
151
+ return NAMED_KEYS[normalized];
152
+ }
153
+
154
+ // Check for ctrl+key
155
+ if (Object.hasOwn(CTRL_KEYS, normalized)) {
156
+ return CTRL_KEYS[normalized];
157
+ }
158
+
159
+ // Parse modifier prefixes: ctrl+alt+shift+key, c-m-s-key, etc.
160
+ let rest = normalized;
161
+ let ctrl = false, alt = false, shift = false;
162
+
163
+ // Support both "ctrl+alt+x" and "c-m-x" syntax
164
+ while (rest.length > 2) {
165
+ if (rest.startsWith("ctrl+") || rest.startsWith("ctrl-")) {
166
+ ctrl = true;
167
+ rest = rest.slice(5);
168
+ } else if (rest.startsWith("alt+") || rest.startsWith("alt-")) {
169
+ alt = true;
170
+ rest = rest.slice(4);
171
+ } else if (rest.startsWith("shift+") || rest.startsWith("shift-")) {
172
+ shift = true;
173
+ rest = rest.slice(6);
174
+ } else if (rest.startsWith("c-")) {
175
+ ctrl = true;
176
+ rest = rest.slice(2);
177
+ } else if (rest.startsWith("m-")) {
178
+ alt = true;
179
+ rest = rest.slice(2);
180
+ } else if (rest.startsWith("s-")) {
181
+ shift = true;
182
+ rest = rest.slice(2);
183
+ } else {
184
+ break;
185
+ }
186
+ }
187
+
188
+ // Handle shift+tab specially
189
+ if (shift && rest === "tab") {
190
+ return "\x1b[Z";
191
+ }
192
+
193
+ // Check if base key is a named key that supports modifiers
194
+ const baseSeq = Object.hasOwn(NAMED_KEYS, rest) ? NAMED_KEYS[rest] : undefined;
195
+ if (baseSeq && MODIFIABLE_KEYS.has(rest) && (ctrl || alt || shift)) {
196
+ const mod = xtermModifier(shift, alt, ctrl);
197
+ if (mod > 1) {
198
+ const modified = applyXtermModifier(baseSeq, mod);
199
+ if (modified) return modified;
200
+ }
201
+ }
202
+
203
+ // For single character with modifiers
204
+ if (rest.length === 1) {
205
+ let char = rest;
206
+ if (shift && /[a-z]/.test(char)) {
207
+ char = char.toUpperCase();
208
+ }
209
+ if (ctrl) {
210
+ const ctrlChar = CTRL_KEYS[`ctrl+${char.toLowerCase()}`];
211
+ if (ctrlChar) char = ctrlChar;
212
+ }
213
+ if (alt) {
214
+ return altKey(char);
215
+ }
216
+ return char;
217
+ }
218
+
219
+ // Named key with alt modifier
220
+ if (baseSeq && alt) {
221
+ return `\x1b${baseSeq}`;
222
+ }
223
+
224
+ // Return base sequence if found
225
+ if (baseSeq) {
226
+ return baseSeq;
227
+ }
228
+
229
+ const close = Object.keys(NAMED_KEYS)
230
+ .map((name) => ({ name, distance: editDistance(name, rest) }))
231
+ .filter(({ distance }) => distance <= 2)
232
+ .sort((a, b) => a.distance - b.distance)
233
+ .slice(0, 3)
234
+ .map(({ name }) => name);
235
+ throw new Error(
236
+ `Unknown key "${token}" in keys.${close.length ? ` Did you mean ${close.join(", ")}?` : ""} ` +
237
+ "Use a named key (up, enter, escape, tab, space, backspace, delete, home, end, pageup, pagedown, f1-f12, kp0-kp9) " +
238
+ "or a single character, optionally prefixed with ctrl+/alt+/shift+ (or c-/m-/s-). Send text with input.",
239
+ );
240
+ }
241
+
242
+ function editDistance(a: string, b: string): number {
243
+ let prev = Array.from({ length: b.length + 1 }, (_, i) => i);
244
+ for (let i = 1; i <= a.length; i++) {
245
+ const row = [i];
246
+ for (let j = 1; j <= b.length; j++) {
247
+ row[j] = Math.min(prev[j] + 1, row[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
248
+ }
249
+ prev = row;
250
+ }
251
+ return prev[b.length];
252
+ }
253
+
254
+ export type InputSpec = string | { text?: string; keys?: string[]; paste?: string; hex?: string[] };
255
+
256
+ /** Translate input specification to terminal escape sequences */
257
+ export function translateInput(input: InputSpec): string {
258
+ if (typeof input === "string") {
259
+ return input;
260
+ }
261
+
262
+ let result = "";
263
+
264
+ // Hex bytes (raw escape sequences)
265
+ if (input.hex?.length) {
266
+ for (const raw of input.hex) {
267
+ const trimmed = raw.trim().toLowerCase();
268
+ const normalized = trimmed.startsWith("0x") ? trimmed.slice(2) : trimmed;
269
+ if (!/^[0-9a-f]{1,2}$/.test(normalized)) throw new Error(`Invalid inputHex byte "${raw}": use one byte from 0x00 to 0xff, for example "0x1b".`);
270
+ result += String.fromCharCode(Number.parseInt(normalized, 16));
271
+ }
272
+ }
273
+
274
+ // Literal text
275
+ if (input.text) {
276
+ result += input.text;
277
+ }
278
+
279
+ // Bracketed paste
280
+ if (input.paste) {
281
+ result += encodePaste(input.paste);
282
+ }
283
+
284
+ // Named keys with modifier support
285
+ if (input.keys) {
286
+ for (const key of input.keys) {
287
+ result += encodeKeyToken(key);
288
+ }
289
+ }
290
+
291
+ return result;
292
+ }
@@ -0,0 +1,37 @@
1
+ // Imported from pi-interactive-shell 0.18.0 pty-protocol.ts (MIT, third-party/licenses/pi-interactive-shell.txt).
2
+ // Full-screen programs block until these queries are answered, so the session replies in output order.
3
+ // PTY control queries emitted by terminal applications.
4
+ // Cursor position DSR: ESC[6n or ESC[?6n. Primary DA: ESC[c or ESC[0c.
5
+ const DEVICE_QUERY_PATTERN = /\x1b\[(\??6n|0?c)/g;
6
+
7
+ export type DeviceQuery = "cursor-position" | "primary-device-attributes";
8
+
9
+ /** Result of splitting PTY output around terminal queries that require a response. */
10
+ export interface DeviceQuerySplit {
11
+ segments: Array<{ text: string; queryAfter: DeviceQuery }>;
12
+ trailingText: string;
13
+ hasQuery: boolean;
14
+ }
15
+
16
+ export function splitAroundDeviceQueries(input: string): DeviceQuerySplit {
17
+ const segments: Array<{ text: string; queryAfter: DeviceQuery }> = [];
18
+ let lastIndex = 0;
19
+ const regex = new RegExp(DEVICE_QUERY_PATTERN.source, "g");
20
+ let match: RegExpExecArray | null;
21
+ while ((match = regex.exec(input)) !== null) {
22
+ segments.push({
23
+ text: input.slice(lastIndex, match.index),
24
+ queryAfter: match[1].endsWith("c") ? "primary-device-attributes" : "cursor-position",
25
+ });
26
+ lastIndex = match.index + match[0].length;
27
+ }
28
+ return { segments, trailingText: input.slice(lastIndex), hasQuery: segments.length > 0 };
29
+ }
30
+
31
+ export function buildCursorPositionResponse(row = 1, col = 1): string {
32
+ return `\x1b[${row};${col}R`;
33
+ }
34
+
35
+ export function buildPrimaryDeviceAttributesResponse(): string {
36
+ return "\x1b[?1;2c";
37
+ }
@@ -0,0 +1,131 @@
1
+ import { READ_LIMITS, type ReadSource } from '../../runtime/read.ts';
2
+
3
+ // Password prompts are an output boundary, distinct from sensitive input logging.
4
+ // The source bytes stay on disk; replace only echoed bytes, retaining every raw offset.
5
+ // Word boundaries are judged on visible text: Windows ConPTY emits CSI sequences such
6
+ // as `ESC[?25h` directly before prompts, and their alphabetic final byte would
7
+ // otherwise defeat `\b`.
8
+ const PASSWORD = /(?:\b|(?<=\x1b\[[0-?]*[ -/]*[@-~]))(?:password|passphrase|passcode|pin(?: code)?)\b[^\r\n::?]{0,80}[::?][ \t]*|(?:密码|口令)[^\r\n::?]{0,80}[::?][ \t]*/iu;
9
+ // Terminal syntax and blanks that draw no glyph; an unterminated sequence at a read
10
+ // boundary is consumed as silent so its tail is not mistaken for echoed text.
11
+ const SILENT = /\x1b(?:\[[0-?]*[ -/]*[@-~]?|\][^\x07\x1b]*(?:\x07|\x1b\\)?|[ -~]?)|[\x00-\x20\x7f]/y;
12
+ const VERTICAL_MOVE = /^\x1b\[[0-?]*[ -/]*[HfAFd]$/;
13
+ const CARRY_BYTES = 256;
14
+ const EMPTY = Buffer.alloc(0);
15
+
16
+ /**
17
+ * hidden: the rest of the current line is echo. pending: a prompt has shown no echo yet.
18
+ * Windows ConPTY repaints after leaving the alternate screen: it redraws the prompt row
19
+ * and blank rows, then moves the cursor back to the prompt (CSI H/f/A/F/d) before the
20
+ * echo. While pending, blank rows are skipped and text drawn after such a move is still
21
+ * hidden; text without a move (sudo's "Sorry, try again") ends the prompt and stays.
22
+ */
23
+ type Mask = { carry: Buffer; hidden: boolean; echo: boolean; pending: boolean; moved: boolean };
24
+
25
+ function tail(bytes: Buffer): Buffer {
26
+ let start = Math.max(0, bytes.length - CARRY_BYTES);
27
+ // A carry starts on a code point boundary, otherwise decoding replacement bytes
28
+ // shifts the prompt's raw-byte end and can leave part of an echo unmasked.
29
+ while (start < bytes.length && (bytes[start] & 0xc0) === 0x80) start++;
30
+ return Buffer.from(bytes.subarray(start));
31
+ }
32
+
33
+ /** First drawn character at or after `from`, and whether a vertical cursor move precedes it. */
34
+ function firstVisible(text: string, from: number): { at: number; moved: boolean } {
35
+ let moved = false;
36
+ for (let index = from; index < text.length;) {
37
+ SILENT.lastIndex = index;
38
+ const silent = SILENT.exec(text);
39
+ if (!silent) return { at: index, moved };
40
+ moved ||= VERTICAL_MOVE.test(silent[0]);
41
+ index += silent[0].length;
42
+ }
43
+ return { at: -1, moved };
44
+ }
45
+
46
+ /** Advance the mask over one line segment of `bytes`, blanking hidden bytes in `output`. */
47
+ function maskSegment(state: Mask, bytes: Buffer, output: Buffer | undefined, from: number, to: number, eol: boolean): void {
48
+ const line = bytes.subarray(from, to), joined = Buffer.concat([state.carry, line]), text = joined.toString('utf8');
49
+ // Byte position in this segment of a UTF-16 index in the carry-prefixed text.
50
+ const at = (index: number) => Math.max(0, Buffer.byteLength(text.slice(0, index)) - state.carry.length);
51
+ let hideFrom = state.hidden ? 0 : -1;
52
+ if (state.hidden) state.echo ||= firstVisible(line.toString('utf8'), 0).at >= 0;
53
+ else {
54
+ const match = PASSWORD.exec(text);
55
+ if (match) {
56
+ const end = match.index + match[0].length;
57
+ hideFrom = at(end); state.hidden = true; state.pending = false;
58
+ state.echo = firstVisible(text, end).at >= 0;
59
+ } else if (state.pending) {
60
+ const first = firstVisible(text, 0);
61
+ state.moved ||= first.moved;
62
+ if (first.at >= 0) {
63
+ state.pending = false;
64
+ if (state.moved) { hideFrom = at(first.at); state.hidden = state.echo = true; }
65
+ }
66
+ }
67
+ }
68
+ if (hideFrom >= 0) output?.fill(32, from + hideFrom, to);
69
+ if (!eol) { state.carry = tail(joined); return; }
70
+ state.pending ||= state.hidden && !state.echo;
71
+ Object.assign(state, { carry: EMPTY, hidden: false, echo: false, moved: false });
72
+ }
73
+
74
+ /** A masked view of the original log, including pages starting after a prompt. */
75
+ export function passwordSafeSource(source: ReadSource): ReadSource {
76
+ let end = 0, state: Mask = { carry: EMPTY, hidden: false, echo: false, pending: false, moved: false };
77
+
78
+ async function lineStart(offset: number): Promise<number> {
79
+ for (let position = offset; position > 0;) {
80
+ const from = Math.max(0, position - READ_LIMITS.chunk), chunk = await source.read(from, position - from);
81
+ const newline = chunk.lastIndexOf(10);
82
+ if (newline >= 0) return from + newline + 1;
83
+ position = from;
84
+ }
85
+ return 0;
86
+ }
87
+ /** Rows above `start`, newest first: blanks keep an unanswered prompt pending, the first drawn row decides. */
88
+ async function pendingAt(start: number): Promise<boolean> {
89
+ for (let end = start - 1; end > 0;) {
90
+ const from = Math.max(0, end - READ_LIMITS.chunk), chunk = await source.read(from, end - from);
91
+ let to = chunk.length;
92
+ for (;;) {
93
+ const newline = to > 0 ? chunk.lastIndexOf(10, to - 1) : -1;
94
+ // A partial first row is reread whole from the next chunk; only an over-long row is judged by its tail.
95
+ if (newline < 0 && from > 0 && to < chunk.length) break;
96
+ const text = chunk.subarray(newline + 1, to).toString('utf8'), match = PASSWORD.exec(text);
97
+ if (match) return firstVisible(text, match.index + match[0].length).at < 0;
98
+ if (firstVisible(text, 0).at >= 0 || newline < 0) return false;
99
+ to = newline;
100
+ }
101
+ end = from + to;
102
+ }
103
+ return false;
104
+ }
105
+ /** Rebuild the mask at a random offset by replaying its line prefix after the rows above. */
106
+ async function context(offset: number): Promise<Mask> {
107
+ const start = await lineStart(offset);
108
+ const next: Mask = { carry: EMPTY, hidden: false, echo: false, pending: await pendingAt(start), moved: false };
109
+ for (let position = start; position < offset;) {
110
+ const chunk = await source.read(position, Math.min(READ_LIMITS.chunk, offset - position));
111
+ if (!chunk.length) break;
112
+ maskSegment(next, chunk, undefined, 0, chunk.length, false);
113
+ position += chunk.length;
114
+ }
115
+ return next;
116
+ }
117
+
118
+ return {size: source.size, close: () => source.close(), async read(offset, length) {
119
+ if (offset !== end) state = await context(offset);
120
+ const bytes = await source.read(offset, length), output = Buffer.from(bytes);
121
+ // Keep only a short raw suffix between sequential reads; a split prompt is
122
+ // recognized without rescanning the whole file or retaining a second transcript.
123
+ for (let from = 0; from < bytes.length;) {
124
+ const newline = bytes.indexOf(10, from), to = newline < 0 ? bytes.length : newline;
125
+ maskSegment(state, bytes, output, from, to, newline >= 0);
126
+ from = to + 1;
127
+ }
128
+ end = offset + bytes.length;
129
+ return output;
130
+ }};
131
+ }