dsh-aiterm 0.0.0-stage → 0.5.1
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.
- package/CONTRACTS.md +794 -0
- package/LICENSE +21 -0
- package/README.md +407 -2
- package/client/AuditPopover.jsx +140 -0
- package/client/ConnectForm.jsx +528 -0
- package/client/HistoryPanel.jsx +562 -0
- package/client/ProfilesPanel.jsx +551 -0
- package/client/QuickScripts.jsx +302 -0
- package/client/ScriptsPanel.jsx +1230 -0
- package/client/Terminal.jsx +424 -0
- package/client/api.js +1273 -0
- package/client/index.js +91 -0
- package/client/locale.js +872 -0
- package/client/macroLang.js +267 -0
- package/client/panel.jsx +873 -0
- package/client/reset.js +111 -0
- package/client/scriptDialect.js +55 -0
- package/client/scriptLang.js +337 -0
- package/client/scriptOrder.js +139 -0
- package/client/store.js +809 -0
- package/client/styles.js +1419 -0
- package/client/terminal-theme.js +136 -0
- package/client/ui.jsx +653 -0
- package/cordis.patch.yml +17 -0
- package/icon.svg +16 -0
- package/lib/client.js +400 -0
- package/lib/host/autolog.js +407 -0
- package/lib/host/batch.js +455 -0
- package/lib/host/config.js +98 -0
- package/lib/host/exporter.js +386 -0
- package/lib/host/history-store.js +909 -0
- package/lib/host/outputlog.js +550 -0
- package/lib/host/permission.js +241 -0
- package/lib/host/profiles.js +657 -0
- package/lib/host/prompt.js +38 -0
- package/lib/host/promptdetect.js +73 -0
- package/lib/host/registry.js +1990 -0
- package/lib/host/routes.js +482 -0
- package/lib/host/screen.js +892 -0
- package/lib/host/screendiff.js +60 -0
- package/lib/host/script-lang.js +1464 -0
- package/lib/host/scripts.js +453 -0
- package/lib/host/tools.js +1441 -0
- package/lib/host/transports/ssh.js +980 -0
- package/lib/host/transports/telnet.js +711 -0
- package/lib/host/util.js +297 -0
- package/lib/index.js +132 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +77 -4
- package/scripts/build-client.mjs +116 -0
- package/scripts/build-vendor.mjs +37 -0
- package/scripts/smoke-client.mjs +2986 -0
- package/vendor/README.md +31 -0
- package/vendor/ssh2.LICENSE +19 -0
- package/vendor/ssh2.cjs +20124 -0
package/CONTRACTS.md
ADDED
|
@@ -0,0 +1,794 @@
|
|
|
1
|
+
# CONTRACTS — @dsh/aiterm
|
|
2
|
+
|
|
3
|
+
Authoritative interface contract for all contributors. Do not change this file; if an
|
|
4
|
+
interface must change, report it to the Lead instead of editing.
|
|
5
|
+
|
|
6
|
+
Package root: `/root/workspace/ssh_telnet/aiterm`
|
|
7
|
+
Package name / bundle row id / client module id: `@dsh/aiterm` (row id `aiterm`)
|
|
8
|
+
|
|
9
|
+
Renamed from `@dsh/dsh-ssh-telnet`: 0.4.0 renamed only the package, 0.5.0 renamed the rest —
|
|
10
|
+
model tool names `aiterm_*`, route prefix `/aiterm`, data directory `~/.dsh/aiterm`, credential
|
|
11
|
+
scope `aiterm/`, localStorage keys `dsh.aiterm.*` and tab kind `aiterm`. No legacy alias is kept.
|
|
12
|
+
Reference implementations to read (read-only, do NOT copy blindly):
|
|
13
|
+
- `/tmp/tgz/dsh-live-terminal/package` — right-sidebar terminal panel, host tools, SSE routes
|
|
14
|
+
- `/tmp/tgz/_xgone_dsh-netshell/package` — SSH sessions, profiles, settings page
|
|
15
|
+
- `/tmp/tgz/dsh-plugin-ssh/package` — ssh2 usage
|
|
16
|
+
|
|
17
|
+
## 0. Ownership / write scopes
|
|
18
|
+
|
|
19
|
+
| Owner | May write |
|
|
20
|
+
|---|---|
|
|
21
|
+
| Lead | `package.json`, `cordis.patch.yml`, `icon.svg`, `locale/**`, `README.md`, `lib/index.js`, `lib/host/{config,permission,registry,routes,tools,prompt,profiles,util}.js` |
|
|
22
|
+
| transport teammate | `lib/host/transports/**`, `lib/host/screen.js`, `test/transport-*.mjs` |
|
|
23
|
+
| client teammate | `client/**`, `scripts/**`, `lib/client.js` |
|
|
24
|
+
| qa teammate | `test/**` (except `test/transport-*`), `tools/**` |
|
|
25
|
+
|
|
26
|
+
Never edit another owner's file. Shared runtime deps are installed by the Lead in the
|
|
27
|
+
package root; client-side deps are bundled by the client build, not required at runtime.
|
|
28
|
+
|
|
29
|
+
## 1. Transport adapter interface (`lib/host/transports/{ssh,telnet}.js`)
|
|
30
|
+
|
|
31
|
+
Both modules export exactly one function:
|
|
32
|
+
|
|
33
|
+
```js
|
|
34
|
+
export async function connect(options, handlers) -> Promise<TransportConnection>
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
`options`:
|
|
38
|
+
```
|
|
39
|
+
{
|
|
40
|
+
host: string, port: number, // telnet: username ignored
|
|
41
|
+
username?: string, // ssh only
|
|
42
|
+
auth?: { type: 'password', password: string }
|
|
43
|
+
| { type: 'privateKey', privateKey: string, passphrase?: string }
|
|
44
|
+
| { type: 'agent' }
|
|
45
|
+
| { type: 'none' }, // default 'none' cols: number, rows: number,
|
|
46
|
+
connectTimeoutMs?: number, // default 15000
|
|
47
|
+
keepaliveMs?: number, // default 15000
|
|
48
|
+
readyTimeoutMs?: number, // default 20000
|
|
49
|
+
hostKeyPolicy?: 'accept-new' | 'strict' | 'insecure', // ssh; default 'accept-new'
|
|
50
|
+
knownHostsPath?: string, // ssh; default <dataDir>/known_hosts
|
|
51
|
+
term?: string, // default 'xterm-256color'
|
|
52
|
+
}
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
`handlers` (all optional except onData):
|
|
56
|
+
```
|
|
57
|
+
{
|
|
58
|
+
onData(chunk: string): void, // ALREADY decoded UTF-8 string; telnet IAC sequences removed
|
|
59
|
+
onReady(info: { hostKeyFingerprint?: string, banner?: string }): void,
|
|
60
|
+
onClose(info: { code?: number|null, signal?: string, reason?: string }): void,
|
|
61
|
+
onError(error: Error): void, // connection-level failure; close is still emitted afterwards at most once
|
|
62
|
+
}
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
`TransportConnection`:
|
|
66
|
+
```js
|
|
67
|
+
{
|
|
68
|
+
readonly kind: 'ssh' | 'telnet',
|
|
69
|
+
readonly ready: Promise<{ hostKeyFingerprint?: string, banner?: string }>, // rejects on connect failure
|
|
70
|
+
write(data: string | Buffer): void, // throws only when not open
|
|
71
|
+
resize(cols: number, rows: number): void,
|
|
72
|
+
close(reason?: string): Promise<void>, // idempotent, resolves after the socket/channel is gone
|
|
73
|
+
readonly state: 'connecting' | 'open' | 'closed',
|
|
74
|
+
}
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Rules:
|
|
78
|
+
- `connect()` resolves once the underlying connection is ESTABLISHED (or the telnet socket
|
|
79
|
+
is connected), not before. Connection failure rejects `connect()` **and** rejects `ready`.
|
|
80
|
+
- `onData` must never receive telnet negotiation bytes; SSH must not receive window-change
|
|
81
|
+
control data. Output must be forwarded in arrival order.
|
|
82
|
+
- `close()` must stop emitting events after it resolves; late events are ignored.
|
|
83
|
+
- No `@deepseek-ai/*` imports. Only Node builtins plus `ssh2` (already a package dependency).
|
|
84
|
+
|
|
85
|
+
## 2. Screen emulator (`lib/host/screen.js`)
|
|
86
|
+
|
|
87
|
+
```js
|
|
88
|
+
export class Screen {
|
|
89
|
+
constructor(options: { cols: number, rows: number, scrollback?: number })
|
|
90
|
+
write(text: string): void // feed raw terminal output (ANSI allowed)
|
|
91
|
+
resize(cols: number, rows: number): void
|
|
92
|
+
snapshot(): { cols, rows, cursor: { x, y }, lines: string[], alt: boolean } // visible screen
|
|
93
|
+
text(): string // visible screen, trailing blank lines trimmed, joined by '\n'
|
|
94
|
+
historyText(maxLines?: number): string // scrollback + visible, oldest first
|
|
95
|
+
dispose(): void
|
|
96
|
+
}
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
Use `@xterm/headless` (`HeadlessTerminal`) + `@xterm/addon-serialize` when available; fall back
|
|
100
|
+
to a small internal ANSI-stripping line buffer if the import fails, so the plugin still works.
|
|
101
|
+
`screenshot`/`read` tools depend on this, so `text()` must be readable and bounded.
|
|
102
|
+
|
|
103
|
+
## 3. Session model
|
|
104
|
+
|
|
105
|
+
Host-side session record (never contains a password or private key):
|
|
106
|
+
|
|
107
|
+
```js
|
|
108
|
+
{
|
|
109
|
+
id: 'st-1', // stable, monotonically increasing
|
|
110
|
+
title: 'root@10.0.0.5',
|
|
111
|
+
transport: 'ssh' | 'telnet',
|
|
112
|
+
host, port, username,
|
|
113
|
+
profileId: string | undefined,
|
|
114
|
+
state: 'connecting' | 'open' | 'closed' | 'failed',
|
|
115
|
+
error: string | undefined,
|
|
116
|
+
cols, rows,
|
|
117
|
+
createdAt: number, updatedAt: number,
|
|
118
|
+
lastActivityAt: number,
|
|
119
|
+
bytesIn: number, bytesOut: number,
|
|
120
|
+
permission: PermissionState,
|
|
121
|
+
}
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
`PermissionState`:
|
|
125
|
+
```js
|
|
126
|
+
{
|
|
127
|
+
aiAccess: 'ro' | 'wo' | 'rw', // AI read/write capability
|
|
128
|
+
lockOwner: 'ai' | 'human' | null, // who holds the exclusive control token
|
|
129
|
+
lockExpiresAt: number | null, // epoch ms; AI lock auto-expires, human lock does not
|
|
130
|
+
humanWriteBlocked: boolean, // derived: lockOwner === 'ai' && config.blockHumanWhileAi
|
|
131
|
+
aiWriteBlocked: boolean, // derived: aiAccess === 'wo' ... etc (see §4)
|
|
132
|
+
}
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
## 4. Permission semantics (authoritative)
|
|
136
|
+
|
|
137
|
+
Sources: `'human'` (browser HTTP path) and `'ai'` (model tools).
|
|
138
|
+
|
|
139
|
+
Read (screen/output/snapshot):
|
|
140
|
+
- human: always allowed.
|
|
141
|
+
- ai: allowed iff `aiAccess ∈ {ro, rw}`.
|
|
142
|
+
|
|
143
|
+
Write (input sent to the remote pty/socket):
|
|
144
|
+
- human: allowed unless `lockOwner === 'ai' && config.blockHumanWhileAi === true`
|
|
145
|
+
→ error code `HUMAN_WRITE_BLOCKED`.
|
|
146
|
+
- ai: requires `aiAccess ∈ {wo, rw}` (else `AI_READ_ONLY` / code `AI_WRITE_DENIED`), and
|
|
147
|
+
`lockOwner !== 'human'` (else `AI_WRITE_DENIED`, "human holds control").
|
|
148
|
+
|
|
149
|
+
Lock lifecycle:
|
|
150
|
+
- An AI write with `config.aiAutoLock === true` (default) sets `lockOwner = 'ai'` and
|
|
151
|
+
`lockExpiresAt = now + config.aiLockIdleMs` (default 30000), refreshed on each AI write.
|
|
152
|
+
A timer clears the lock when it expires.
|
|
153
|
+
- `lock.takeOver` (human action) sets `lockOwner = 'human'` (AI writes are then denied until
|
|
154
|
+
released). `lock.release` (human action) sets `lockOwner = null` and clears expiry.
|
|
155
|
+
- `config.blockHumanWhileAi === false` disables human-write blocking (pure coexistence mode).
|
|
156
|
+
- `config.aiAccessDefault` default `'rw'`; each new session starts from it.
|
|
157
|
+
|
|
158
|
+
User-only actions (never callable from a tool): `permission.set`, `lock.takeOver`,
|
|
159
|
+
`lock.release`, `profiles.save`, `profiles.delete`. The registry methods take an `actor`
|
|
160
|
+
argument and reject when `actor === 'ai'`.
|
|
161
|
+
|
|
162
|
+
Audit: every read/write/deny appends `{ at, sessionId, source, action: 'read'|'write'|'deny'|'lock', detail, byteLength }`
|
|
163
|
+
to a bounded per-session ring (last 200). Never log secret data; for writes log the
|
|
164
|
+
first 200 chars with newlines escaped.
|
|
165
|
+
|
|
166
|
+
## 5. Wire protocol (Host HTTP + SSE)
|
|
167
|
+
|
|
168
|
+
All routes under `/aiterm`. Authenticated by `ctx.connection.admit(req)`; any
|
|
169
|
+
non-admitted request gets 401/403. JSON only.
|
|
170
|
+
|
|
171
|
+
`POST /aiterm/rpc`
|
|
172
|
+
Body: `{ "method": string, "params": object }`
|
|
173
|
+
Response: `{ "ok": true, "result": any }` or
|
|
174
|
+
`{ "ok": false, "error": { "code": string, "message": string } }`.
|
|
175
|
+
|
|
176
|
+
Methods (params → result):
|
|
177
|
+
| method | params | result |
|
|
178
|
+
|---|---|---|
|
|
179
|
+
| `sessions.list` | `{}` | `{ sessions: SessionInfo[] }` |
|
|
180
|
+
| `sessions.create` | `{ transport, profileId?, host?, port?, username?, auth?, password?, privateKey?, passphrase?, title?, cols?, rows? }` | `{ session }` |
|
|
181
|
+
| `sessions.close` | `{ id }` | `{ ok: true }` |
|
|
182
|
+
| `sessions.rename` | `{ id, title }` | `{ session }` |
|
|
183
|
+
| `sessions.resize` | `{ id, cols, rows }` | `{ ok: true }` |
|
|
184
|
+
| `sessions.replay` | `{ id }` | `{ session, replay: base64 }` |
|
|
185
|
+
| `sessions.input` | `{ id, data }` | `{ ok: true }` (source `human`) |
|
|
186
|
+
| `permission.get` | `{ id }` | `{ permission }` |
|
|
187
|
+
| `permission.set` | `{ id, aiAccess }` | `{ permission }` (human only) |
|
|
188
|
+
| `lock.takeOver` | `{ id }` | `{ permission }` (human only) |
|
|
189
|
+
| `lock.release` | `{ id }` | `{ permission }` (human only) |
|
|
190
|
+
| `profiles.list` | `{}` | `{ profiles: ProfileInfo[] }` |
|
|
191
|
+
| `profiles.save` | `{ profile }` | `{ profile }` (human only) |
|
|
192
|
+
| `profiles.delete` | `{ id }` | `{ ok: true }` (human only) |
|
|
193
|
+
| `audit.list` | `{ id?, limit? }` | `{ entries: AuditEntry[], sessions?: SessionInfo[] }` |
|
|
194
|
+
|
|
195
|
+
`ProfileInfo`:
|
|
196
|
+
```js
|
|
197
|
+
{ id, name, transport: 'ssh'|'telnet', host, port, username, authType: 'password'|'privateKey'|'agent'|'none',
|
|
198
|
+
hasPassword: boolean, hasPrivateKey: boolean, updatedAt: number }
|
|
199
|
+
```
|
|
200
|
+
Private keys may be stored in the profile; passwords are stored via `ctx.credentials`
|
|
201
|
+
(see §7) and are never returned.
|
|
202
|
+
|
|
203
|
+
`GET /aiterm/events` (global, no query) — SSE, `data: <json>` frames:
|
|
204
|
+
- `{ "type": "sessions", "sessions": SessionInfo[] }` immediately and on any list change
|
|
205
|
+
- `{ "type": "state", "session": SessionInfo }` on state/permission/lock changes
|
|
206
|
+
- `{ "type": "audit", "entry": AuditEntry }`
|
|
207
|
+
|
|
208
|
+
`GET /aiterm/events?sessionId=<id>` — SSE per session:
|
|
209
|
+
- `{ "type": "hello", "session": SessionInfo, "replay": base64 }` (replay = retained raw output bytes)
|
|
210
|
+
- `{ "type": "data", "chunk": base64 }` (raw pty bytes; client writes them to xterm)
|
|
211
|
+
- `{ "type": "state", "session": SessionInfo }`
|
|
212
|
+
- `{ "type": "exit", "code": number|null, "reason": string }`
|
|
213
|
+
- `{ "type": "audit", "entry": AuditEntry }`
|
|
214
|
+
|
|
215
|
+
Heartbeat comment line `:\n\n` every 20s. Close the SSE response when the session closes,
|
|
216
|
+
after sending `exit`.
|
|
217
|
+
|
|
218
|
+
## 6. Client contract
|
|
219
|
+
|
|
220
|
+
Client artifact: `lib/client.js`, CommonJS wrapper exactly like:
|
|
221
|
+
|
|
222
|
+
```js
|
|
223
|
+
window.__ModuleLoader__.load({
|
|
224
|
+
id: '@dsh/aiterm',
|
|
225
|
+
factory(require) {
|
|
226
|
+
...bundled CJS...
|
|
227
|
+
return module.exports // { inject: [...], apply(ctx) {} }
|
|
228
|
+
},
|
|
229
|
+
})
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
`package.json` declares `"dsh": { "bundle": { "patch": "./cordis.patch.yml" },
|
|
233
|
+
"client": { "platform": "web", "immediately": true,
|
|
234
|
+
"inject": ["@deepseek-ai/dsh-client-ui-sidebar-right"] } }`.
|
|
235
|
+
|
|
236
|
+
Client plugin exports `inject` (at least `['slots']`) and `apply(ctx)`. Available on ctx:
|
|
237
|
+
`ctx.slots`, `ctx.locale`, `ctx.effect`, `ctx.sidebarRightTabs` (register tab types),
|
|
238
|
+
`ctx.sidebarRight` (openTab / isExpanded). Do **not** `require('@deepseek-ai/*')` except
|
|
239
|
+
`react` and `react/jsx-runtime`; do not import client primitives — write the controls.
|
|
240
|
+
|
|
241
|
+
Tab type registration (proven by dsh-live-terminal):
|
|
242
|
+
```js
|
|
243
|
+
const off = ctx.sidebarRightTabs.register({
|
|
244
|
+
id: '@dsh/aiterm',
|
|
245
|
+
kind: 'aiterm',
|
|
246
|
+
multiple: false,
|
|
247
|
+
priority: 'extension',
|
|
248
|
+
title: () => t('title'),
|
|
249
|
+
guide: [{ id: 'open', order: 30, title: () => t('title'), description: () => t('guide') }],
|
|
250
|
+
})
|
|
251
|
+
ctx.slots.inject('sidebar.right.pane.tab', () => ctx.slots.register({
|
|
252
|
+
name: 'sidebar.right.pane.tab', key: 'aiterm', locale: 'aiterm',
|
|
253
|
+
inject: (props) => ({ sessionId: props.sessionId }),
|
|
254
|
+
}, PanelComponent))
|
|
255
|
+
ctx.sidebarRight.openTab('aiterm', { revealIfOpened: true })
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
Client duties (v1):
|
|
259
|
+
1. Session rail: list all sessions from RPC + global SSE, state dot, title, transport icon;
|
|
260
|
+
click selects; a `+` opens the connect form.
|
|
261
|
+
2. xterm.js terminal bound to `/aiterm/events?sessionId=`, sending keystrokes via
|
|
262
|
+
`sessions.input`; resize on container resize; "reconnect" via `sessions.replay`.
|
|
263
|
+
3. Input is disabled (read-only + visible banner) when `permission.humanWriteBlocked` is true.
|
|
264
|
+
4. Control bar: AI permission segmented control `只读 / 只写 / 读写`, lock indicator,
|
|
265
|
+
`接管` / `交还 AI` buttons, `审计` popover, close session.
|
|
266
|
+
5. Connect form (modal or inline): profile picker + transport, host, port, username,
|
|
267
|
+
auth type, password (write-only field), private key (textarea), save-as-profile.
|
|
268
|
+
6. All visible text through `ctx.locale` (namespace `aiterm`, zh + en dictionaries).
|
|
269
|
+
7. Styling only with theme tokens (`var(--dsw-alias-*)`); no literal colors except terminal
|
|
270
|
+
theme defaults. Query `Theme.listTokens` for real token names.
|
|
271
|
+
|
|
272
|
+
Client build: `scripts/build-client.mjs` uses esbuild (`npm i -D esbuild @xterm/xterm
|
|
273
|
+
@xterm/addon-fit` inside the package) with `--bundle --format=cjs --platform=browser`,
|
|
274
|
+
externals `react`, `react-dom`, `react/jsx-runtime`, `@deepseek-ai/*`, then wraps the output
|
|
275
|
+
in the ModuleLoader factory and writes `lib/client.js`. `npm run build` must reproduce it.
|
|
276
|
+
|
|
277
|
+
## 7. Storage & config
|
|
278
|
+
|
|
279
|
+
Data dir: `path.join(os.homedir(), '.dsh', 'aiterm')`.
|
|
280
|
+
- `profiles.json` — `{ version: 1, profiles: [...] }`, mode 0600, atomic write.
|
|
281
|
+
- `known_hosts` — ssh host keys (accept-new by default).
|
|
282
|
+
|
|
283
|
+
### Credentials: use the RECORDS API, never the refs API
|
|
284
|
+
|
|
285
|
+
> **Incident (2026-10-21).** v1 stored per-profile secrets as
|
|
286
|
+
> `ctx.credentials.set('aiterm/' + profileId, password)`. That is the *refs*
|
|
287
|
+
> API, whose keys are `CredentialRef` names and MUST match
|
|
288
|
+
> `/^[A-Za-z_][A-Za-z0-9_]*$/`. `aiterm/p-ppmxqcyt` does not, so the
|
|
289
|
+
> credentials document was written into an unparsable state — the write itself
|
|
290
|
+
> did not throw, and DSH then **refused to start on the next boot**
|
|
291
|
+
> (`startup failed: 1 required plugin did not activate → credentials`), taking
|
|
292
|
+
> 11 dependants with it.
|
|
293
|
+
|
|
294
|
+
Rules that follow, enforced by `test/secrets.test.mjs`:
|
|
295
|
+
|
|
296
|
+
- Per-profile secrets go through the **records** API only:
|
|
297
|
+
`modifyRecord(key, async () => ({ kind: 'api-key', key: value }))`,
|
|
298
|
+
`readRecord(key)`, `deleteRecord(key)`.
|
|
299
|
+
- A record key is a `CredentialKey`: exactly `<scope>/<id>`, each segment matching
|
|
300
|
+
`/^[a-z][a-z0-9-]*$/`. Scope is always `aiterm`; the id comes only from
|
|
301
|
+
`credentialSegmentFor(profileId)`, which lowercases, replaces illegal runs,
|
|
302
|
+
prefixes `p-` when the id starts with a digit, and appends a short hash whenever
|
|
303
|
+
the mapping changed the id (so distinct ids can never collapse).
|
|
304
|
+
- Slot suffixes: password `''`, private key `'-key'`, passphrase `'-pass'`.
|
|
305
|
+
- `isCredentialKey(key)` is checked before every write; an illegal key throws
|
|
306
|
+
`BAD_CREDENTIAL_KEY` instead of touching the durable document.
|
|
307
|
+
- Never call `set`/`unset`/`resolve` with a per-profile name. The refs API is for
|
|
308
|
+
environment-variable-named secrets (e.g. `UNIAPI_API_KEY`), not per-record data.
|
|
309
|
+
- A credentials backend failure falls back to `<dataDir>/secrets.json` (0600) and
|
|
310
|
+
logs one warning; saving a profile must never fail because storage failed.
|
|
311
|
+
|
|
312
|
+
`Config` (row config in cordis.patch.yml), all optional with defaults:
|
|
313
|
+
```yaml
|
|
314
|
+
aiAccessDefault: rw # ro | wo | rw
|
|
315
|
+
aiAutoLock: true # AI write acquires the control lock
|
|
316
|
+
aiLockIdleMs: 30000 # AI lock auto-release after this idle time
|
|
317
|
+
blockHumanWhileAi: true # the requested behavior: human typing is blocked while AI operates
|
|
318
|
+
humanCanPreempt: true # UI may always take over
|
|
319
|
+
maxSessions: 16
|
|
320
|
+
scrollback: 4000
|
|
321
|
+
aiReadMaxBytes: 65536
|
|
322
|
+
replayBufferBytes: 262144
|
|
323
|
+
routePath: /aiterm
|
|
324
|
+
enabled: true
|
|
325
|
+
```
|
|
326
|
+
|
|
327
|
+
## 8. Agent tools (registered by Lead in `lib/host/tools.js`)
|
|
328
|
+
|
|
329
|
+
`aiterm_list`, `aiterm_connect`, `aiterm_read`, `aiterm_send`,
|
|
330
|
+
`aiterm_screenshot`, `aiterm_status`, `aiterm_close`, `aiterm_audit`,
|
|
331
|
+
`aiterm_release_control`.
|
|
332
|
+
|
|
333
|
+
Every tool routes through the same registry methods as the UI, respecting §4. Tools must
|
|
334
|
+
never return passwords. Descriptions must state the permission rules so the model knows
|
|
335
|
+
why a write may be refused.
|
|
336
|
+
|
|
337
|
+
### Result payload rule (learned from live verification)
|
|
338
|
+
|
|
339
|
+
The Host validates a tool result as **lossless JSON** and against the tool's declared
|
|
340
|
+
`output.schema` (`additionalProperties: false` where declared). Therefore:
|
|
341
|
+
|
|
342
|
+
- `registry.info()` omits absent optional fields (`profileId`, `error`,
|
|
343
|
+
`hostKeyFingerprint`) instead of emitting `undefined`.
|
|
344
|
+
- Every tool's `execute` return value passes through `jsonSafe()` (drops undefined, nulls
|
|
345
|
+
non-finite numbers, base64-encodes Buffers).
|
|
346
|
+
- A field the implementation returns must be declared in `output.schema`; `type: [...]`
|
|
347
|
+
arrays are rejected — use `oneOf`. `test/tools.test.mjs` enforces both rules.
|
|
348
|
+
|
|
349
|
+
---
|
|
350
|
+
|
|
351
|
+
# v2 增补:增量读取、时间戳历史、批量与脚本
|
|
352
|
+
|
|
353
|
+
> 本节在 v1 基础上增补,v1 的既有接口保持向后兼容(`read` 的 `screen`/`history`/`tail` 继续有效,
|
|
354
|
+
> `screenshot` 保留但精简载荷)。所有实现必须遵守 §8 的“结果载荷规则”(lossless JSON +
|
|
355
|
+
> declared schema,禁止 `type: [...]`)。
|
|
356
|
+
|
|
357
|
+
## 9. 输出日志与游标(`lib/host/outputlog.js`)
|
|
358
|
+
|
|
359
|
+
```js
|
|
360
|
+
export class OutputLog {
|
|
361
|
+
constructor(options: { maxBytes: number, maxAgeMs: number })
|
|
362
|
+
/** 追加一段已解码文本;offset 以 UTF-8 字节累加。 */
|
|
363
|
+
append(text: string, at?: number): void
|
|
364
|
+
/** 当前输出流的总字节偏移(下一个 delta 从这开始)。 */
|
|
365
|
+
get totalOffset(): number
|
|
366
|
+
/** 按偏移取文本。from 缺省 0;maxBytes 缺省不限(内部仍受保留窗口限制)。 */
|
|
367
|
+
slice(from?: number, maxBytes?: number): { text: string, from: number, to: number, truncated: boolean }
|
|
368
|
+
/** 距离给定时间戳之后(含)的第一个字节偏移。 */
|
|
369
|
+
offsetAt(timestampMs: number): number
|
|
370
|
+
/** 首个/末个时间戳,供历史查询报边界。 */
|
|
371
|
+
get window(): { firstAt: number, lastAt: number, firstOffset: number, lastOffset: number }
|
|
372
|
+
/**
|
|
373
|
+
* 在保留窗口内搜索。pattern 为正则;since/until 为 epoch ms。
|
|
374
|
+
* 返回按时间升序的匹配,含上下文行;同时返回扫描字节数与是否截断。
|
|
375
|
+
*/
|
|
376
|
+
search(query: {
|
|
377
|
+
pattern: RegExp, since?: number, until?: number,
|
|
378
|
+
context?: number, maxMatches?: number, maxBytes?: number,
|
|
379
|
+
}): { matches: Array<{ at: number, offset: number, line: string, before: string[], after: string[] }>, scannedBytes: number, truncated: boolean }
|
|
380
|
+
/** 丢弃超出 maxBytes / maxAgeMs 的旧分片。 */
|
|
381
|
+
prune(now?: number): void
|
|
382
|
+
dispose(): void
|
|
383
|
+
}
|
|
384
|
+
```
|
|
385
|
+
|
|
386
|
+
规则:
|
|
387
|
+
- 分片按到达顺序保存 `{ offset, at, text }`;`offset` 为累计 UTF-8 字节数,单调递增。
|
|
388
|
+
- `append` 不抛异常;同一毫秒多片允许合并。
|
|
389
|
+
- 内容裁剪只影响内存窗口,不影响 `totalOffset`(偏移永不回退),这样旧游标只会在 `slice` 里返回
|
|
390
|
+
`truncated: true`,不会错位。
|
|
391
|
+
|
|
392
|
+
## 10. 历史落盘(`lib/host/history-store.js`)
|
|
393
|
+
|
|
394
|
+
目录:`<dataDir>/history/`,`<dataDir>` 默认 `~/.dsh/aiterm`。
|
|
395
|
+
|
|
396
|
+
- `<sessionId>.ndjson`:每行 `{"t":<epoch ms>,"d":"<base64 UTF-8>"}`,一次会话一个文件。
|
|
397
|
+
- `index.json`:`{ "version": 1, "sessions": [CatalogEntry] }`。
|
|
398
|
+
- `CatalogEntry`:`{ id, title, transport, host, port, username, createdAt, closedAt?, bytes, lastTs }`。
|
|
399
|
+
|
|
400
|
+
```js
|
|
401
|
+
export class HistoryStore {
|
|
402
|
+
constructor(options: {
|
|
403
|
+
dir: string,
|
|
404
|
+
retentionMs: number, // 默认 24h
|
|
405
|
+
maxBytesPerSession: number, // 默认 8 MiB
|
|
406
|
+
maxSessions: number, // 默认 100
|
|
407
|
+
flushIntervalMs?: number, // 默认 250
|
|
408
|
+
log?: (level: string, message: string) => void,
|
|
409
|
+
})
|
|
410
|
+
async init(): Promise<void> // 建目录、读 index、按保留策略清理
|
|
411
|
+
async openSession(meta: { id, title, transport, host, port, username, createdAt }): Promise<void>
|
|
412
|
+
appendChunk(sessionId: string, text: string, at?: number): void // 缓冲后异步落盘,不抛
|
|
413
|
+
async flush(sessionId?: string): Promise<void>
|
|
414
|
+
async closeSession(sessionId: string, info?: { closedAt?: number }): Promise<void>
|
|
415
|
+
async listSessions(query?: { limit?: number, since?: number, until?: number }): Promise<CatalogEntry[]>
|
|
416
|
+
/** 查询已关闭/历史会话(也可查仍活跃会话,调用方优先用 OutputLog)。 */
|
|
417
|
+
async query(query: {
|
|
418
|
+
sessionId: string, since?: number, until?: number, search?: string,
|
|
419
|
+
context?: number, maxMatches?: number, maxBytes?: number,
|
|
420
|
+
}): Promise<{ matches: Array<{ at: number, line: string, before: string[], after: string[] }>, scannedBytes: number, truncated: boolean, entry?: CatalogEntry }>
|
|
421
|
+
async prune(now?: number): Promise<void>
|
|
422
|
+
async dispose(): Promise<void>
|
|
423
|
+
}
|
|
424
|
+
```
|
|
425
|
+
|
|
426
|
+
规则:
|
|
427
|
+
- `appendChunk` 只写内存缓冲;`flushIntervalMs` 到点或缓冲超过 64 KiB 时追加写文件(`appendFile`)。
|
|
428
|
+
- 任何磁盘错误只记 warn,绝不影响终端会话。
|
|
429
|
+
- 单文件超过 `maxBytesPerSession` 时截断(重写为尾部内容),并在 catalog 记 `truncatedAt`。
|
|
430
|
+
- `query` 最多扫描文件末尾 `maxBytes`(默认 8 MiB)字节,`truncated` 表示是否因上限截断。
|
|
431
|
+
|
|
432
|
+
## 11. 批量与脚本(`lib/host/batch.js`、`lib/host/scripts.js`)
|
|
433
|
+
|
|
434
|
+
### 11.1 步骤定义(BatchStep)
|
|
435
|
+
|
|
436
|
+
```js
|
|
437
|
+
{
|
|
438
|
+
sessionId?: string, // 省略时用 targets 当前目标
|
|
439
|
+
send: string, // 要发送的文本(可含 {{param}})
|
|
440
|
+
enter?: boolean, // 追加 \r
|
|
441
|
+
waitFor?: { pattern?: string, idleMs?: number, timeoutMs?: number }, // 等待条件
|
|
442
|
+
waitMs?: number, // 固定等待(与 waitFor 二选一,优先 waitFor)
|
|
443
|
+
read?: 'delta' | 'screen' | 'none', // 默认 'delta'
|
|
444
|
+
maxLines?: number, // read 为 screen 时保留行数
|
|
445
|
+
}
|
|
446
|
+
```
|
|
447
|
+
|
|
448
|
+
### 11.2 执行器
|
|
449
|
+
|
|
450
|
+
```js
|
|
451
|
+
export async function runBatch(registry, steps, options): Promise<BatchResult>
|
|
452
|
+
// registry 需提供(见 §13):write(id, text, 'ai')、waitFor(id, opts)、readDelta(id, opts)、
|
|
453
|
+
// readScreen(id, opts)、atPrompt(id)、info(id)
|
|
454
|
+
// options: {
|
|
455
|
+
// targets: string[], // 必填,至少一个;扇出时按顺序逐目标执行整组步骤
|
|
456
|
+
// stopOnError?: boolean, // 默认 true
|
|
457
|
+
// maxTotalMs?: number, // 默认 120000;超时中止并在结果里标 timedOut
|
|
458
|
+
// parallel?: boolean, // 默认 false;true 时各目标并发
|
|
459
|
+
// label?: string, // 审计标签,如 'batch' 或 'script:<name>'
|
|
460
|
+
// }
|
|
461
|
+
// BatchResult: {
|
|
462
|
+
// ok: boolean, timedOut: boolean, label?: string,
|
|
463
|
+
// runs: Array<{
|
|
464
|
+
// sessionId: string, ok: boolean,
|
|
465
|
+
// steps: Array<{ index: number, ok: boolean, matched?: boolean,
|
|
466
|
+
// text?: string, cursor?: string, error?: string }>,
|
|
467
|
+
// stoppedAt?: number,
|
|
468
|
+
// }>,
|
|
469
|
+
// }
|
|
470
|
+
```
|
|
471
|
+
|
|
472
|
+
规则:
|
|
473
|
+
- 每个 `send` 仍然调用 `registry.write(..., 'ai')`,权限拒绝即该步 `ok:false` + `error`,按 `stopOnError` 决定是否继续。
|
|
474
|
+
- 每步文本经 `maxBytes`(默认 8192)截断;整份结果总量再受上限约束。
|
|
475
|
+
- 任何异常都转成步骤级 `error`,`runBatch` 本身不抛(除非 `targets` 为空)。
|
|
476
|
+
|
|
477
|
+
### 11.3 脚本存储
|
|
478
|
+
|
|
479
|
+
目录:`<dataDir>/scripts/<name>.json`(name 仅 `[A-Za-z0-9_-]{1,64}`)。
|
|
480
|
+
|
|
481
|
+
```js
|
|
482
|
+
export class ScriptStore {
|
|
483
|
+
constructor(options: { dir: string, log?: Function })
|
|
484
|
+
async init(): Promise<void>
|
|
485
|
+
async list(): Promise<ScriptSummary[]> // { name, description, params, stepCount, updatedAt }
|
|
486
|
+
async get(name: string): Promise<ScriptDefinition | undefined>
|
|
487
|
+
async save(input: unknown, actor: 'human' | 'ai'): Promise<ScriptSummary>
|
|
488
|
+
async delete(name: string): Promise<boolean>
|
|
489
|
+
/** {{param}} 替换 + 参数校验;缺参且无默认值时抛 coded('MISSING_PARAM')。 */
|
|
490
|
+
render(definition: ScriptDefinition, params?: Record<string, unknown>): BatchStep[]
|
|
491
|
+
}
|
|
492
|
+
```
|
|
493
|
+
|
|
494
|
+
`ScriptDefinition`:`{ name, description, params: Record<string, { default?: string, description?: string }>, steps: BatchStep[], updatedAt }`。
|
|
495
|
+
`ScriptSummary`:`{ name, description, params, stepCount, updatedAt }`。
|
|
496
|
+
|
|
497
|
+
规则:脚本是纯数据,不 eval;禁含密码/私钥字段(发现即拒绝保存)。
|
|
498
|
+
|
|
499
|
+
## 12. v2 工具面与 RPC
|
|
500
|
+
|
|
501
|
+
### 12.1 模型工具(新增/变更)
|
|
502
|
+
|
|
503
|
+
| 工具 | 参数 | 说明 |
|
|
504
|
+
|---|---|---|
|
|
505
|
+
| `aiterm_read` | `{ sessionId, mode?, cursor?, maxBytes?, maxLines?, changedOnly?, reader? }` | `mode` 默认改为 **`delta`**;`screen/history/tail` 保留 |
|
|
506
|
+
| `aiterm_screen` | `{ sessionId, changedOnly?, maxLines?, cursor? }` | 可见屏幕文本(去空行、可只回变化行),返回 `cursor`/`atPrompt`/`unchanged` |
|
|
507
|
+
| `aiterm_screenshot` | `{ sessionId }` | **兼容别名**,载荷精简为 `{ text, cols, rows, cursor, atPrompt, session }`(不再重复 `screen`+`text`) |
|
|
508
|
+
| `aiterm_wait` | `{ sessionId, until?, pattern?, idleMs?, timeoutMs?, cursor?, includeOutput? }` | `until`: `idle`(默认)/`pattern`/`exit` |
|
|
509
|
+
| `aiterm_history` | `{ sessionId?, since?, until?, search?, context?, maxMatches?, maxBytes?, limit? }` | 省略 `sessionId` 时返回会话目录;否则返回匹配/片段 |
|
|
510
|
+
| `aiterm_batch` | `{ steps, targets?, stopOnError?, maxTotalMs?, parallel?, label? }` | §11.2 |
|
|
511
|
+
| `aiterm_script_list` | `{}` | 列出脚本 |
|
|
512
|
+
| `aiterm_script_run` | `{ name, params?, sessionId?, targets? }` | 执行脚本(等价 batch,label=`script:<name>`) |
|
|
513
|
+
|
|
514
|
+
时间参数 `since`/`until` 接受:epoch 毫秒数字、ISO 字符串、或相对量 `"10m"` / `"2h"` / `"90s"`。
|
|
515
|
+
|
|
516
|
+
### 12.2 读取语义
|
|
517
|
+
|
|
518
|
+
- 游标 `cursor` 是不透明字符串(实现为十进制字节偏移)。省略时使用该读者(`reader`,默认 `ai`)在 Host 侧保存的上次位置。
|
|
519
|
+
- `delta`:返回新输出 + 新 `cursor`;无新内容时 `text: ""`、`newBytes: 0`(约 10 token,这是核心省 token 手段)。
|
|
520
|
+
- `screen`:`changedOnly: true` 时只回相对该读者上次屏幕发生变化的行,前缀 `L<n>:`;完全没变化时 `unchanged: true`、`text: ""`。
|
|
521
|
+
- 所有读取仍受 §4 权限约束(`wo` 拒绝读)。
|
|
522
|
+
- 所有读取返回 `atPrompt`(基于 `config.promptPattern`)。
|
|
523
|
+
|
|
524
|
+
### 12.3 RPC(浏览器 → Host)
|
|
525
|
+
|
|
526
|
+
在 §5 基础上新增:
|
|
527
|
+
|
|
528
|
+
| method | params | result |
|
|
529
|
+
|---|---|---|
|
|
530
|
+
| `read.delta` | `{ id, cursor?, maxBytes? }` | `{ text, cursor, newBytes, atPrompt }` |
|
|
531
|
+
| `read.screen` | `{ id, changedOnly?, maxLines? }` | `{ text, changedLines, cursor, atPrompt, unchanged }` |
|
|
532
|
+
| `history.sessions` | `{ limit?, since?, until? }` | `{ sessions: CatalogEntry[] }` |
|
|
533
|
+
| `history.query` | `{ sessionId?, since?, until?, search?, context?, maxMatches?, maxBytes?, limit? }` | `{ sessions?: CatalogEntry[], matches?: Match[], truncated, scannedBytes }` |
|
|
534
|
+
| `scripts.list` | `{}` | `{ scripts: ScriptSummary[] }` |
|
|
535
|
+
| `scripts.save` | `{ script }` | `{ script: ScriptSummary }`(human only) |
|
|
536
|
+
| `scripts.delete` | `{ name }` | `{ ok: boolean }`(human only) |
|
|
537
|
+
| `scripts.run` | `{ name, params?, sessionId?, targets? }` | `{ result: BatchResult }` |
|
|
538
|
+
| `batch.run` | `{ steps, targets?, stopOnError?, maxTotalMs?, parallel?, label? }` | `{ result: BatchResult }` |
|
|
539
|
+
|
|
540
|
+
SSE 新增帧(全局流):`{ "type": "batch", "batchId": string, "label"?: string, "state": "step" | "done", "sessionId": string, "stepIndex": number, "ok": boolean, "text"?: string, "error"?: string }`。
|
|
541
|
+
|
|
542
|
+
### 12.4 Config 增补
|
|
543
|
+
|
|
544
|
+
```yaml
|
|
545
|
+
promptPattern: '(?:^|[\s\])~:])[#$%>❯»]\s*
|
|
546
|
+
historyRetentionMs: 86400000 # 落盘历史保留 24h
|
|
547
|
+
historyMaxBytesPerSession: 8388608 # 单会话历史 8MiB
|
|
548
|
+
historyMaxSessions: 100 # 历史会话数量上限
|
|
549
|
+
deltaDefaultMaxBytes: 8192 # delta 单次上限
|
|
550
|
+
scriptsDir: scripts # <dataDir> 下脚本目录名
|
|
551
|
+
```
|
|
552
|
+
# 提示符识别
|
|
553
|
+
historyRetentionMs: 86400000 # 落盘历史保留 24h
|
|
554
|
+
historyMaxBytesPerSession: 8388608 # 单会话历史 8MiB
|
|
555
|
+
historyMaxSessions: 100 # 历史会话数量上限
|
|
556
|
+
deltaDefaultMaxBytes: 8192 # delta 单次上限
|
|
557
|
+
scriptsDir: scripts # <dataDir> 下脚本目录名
|
|
558
|
+
```
|
|
559
|
+
|
|
560
|
+
### 12.5 游标与等待的语义(验证后补充)
|
|
561
|
+
|
|
562
|
+
- **只有成功的等待才消耗游标**。`waitFor` 命中(`matched: true`)时把该读者的 delta 游标推进到
|
|
563
|
+
当前末尾;超时(`matched: false`)时**不推进**,期间产生的输出仍可被下一次 delta 读到。
|
|
564
|
+
- **等待默认从该读者上次读到的位置开始扫描**(而非"从此刻起"),因此"发送 → 等待匹配回显"这种
|
|
565
|
+
调用顺序不会因为输出先到而漏匹配;从未读过的读者则从最近 `aiReadMaxBytes` 的窗口开始。
|
|
566
|
+
- `changedOnly` 的基线来自该读者上一次 screen 读;**首次**调用时基线为空,全部行都算变化
|
|
567
|
+
(`added` 也要计入),不会返回"无变化"。
|
|
568
|
+
- `atPrompt` = 屏幕最后一行非空内容以提示符字符结尾 **且** 光标停在该行(提示符不换行);
|
|
569
|
+
只看正则不足以区分"输出恰好以 $ 结尾",两者组合才既覆盖 `mock$`/`bash-5.2$` 又不误判普通输出。
|
|
570
|
+
|
|
571
|
+
---
|
|
572
|
+
|
|
573
|
+
# v3 增补:配置管理与脚本语言
|
|
574
|
+
|
|
575
|
+
## 13. 配置(profile)管理
|
|
576
|
+
|
|
577
|
+
`ProfileInfo` 增加两个字段(其余不变):
|
|
578
|
+
|
|
579
|
+
```js
|
|
580
|
+
{
|
|
581
|
+
...v2 字段,
|
|
582
|
+
folder: string, // 分组名,'' 表示未分组;≤64 字符,无控制字符
|
|
583
|
+
order: number, // 组内排序(升序),同组内唯一性不强制
|
|
584
|
+
}
|
|
585
|
+
```
|
|
586
|
+
|
|
587
|
+
行为:
|
|
588
|
+
|
|
589
|
+
- `profiles.save` 保持"创建或更新"语义,接受可选 `folder` / `order`(省略时保留原值)。
|
|
590
|
+
- 改名只改显示名,不改 `id`(`id` 是凭据键的一部分,改 id 会丢密码):
|
|
591
|
+
`profiles.rename { id, name } → { profile }`,name 1–120 字符。
|
|
592
|
+
- 移动分组:`profiles.setFolder { id, folder } → { profile }`。
|
|
593
|
+
- 删除:沿用 `profiles.delete { id } → { ok }`,同时删除该配置的三个凭据槽位。
|
|
594
|
+
- 列表附带分组概览:`profiles.list {} → { profiles, folders: [{ name, count }] }`
|
|
595
|
+
(`folders` 由去重后的 `folder` 生成,`''` 不入列)。
|
|
596
|
+
- 所有配置写操作**仅限 human**(AI 不可调用,与凭据安全一致)。
|
|
597
|
+
|
|
598
|
+
## 14. 脚本语言(`lib/host/script-lang.js`)
|
|
599
|
+
|
|
600
|
+
脚本定义(脚本文件仍是 `<dataDir>/scripts/<name>.json`):
|
|
601
|
+
|
|
602
|
+
```js
|
|
603
|
+
{
|
|
604
|
+
name, description, folder?: string, // folder 可空
|
|
605
|
+
params: { [name]: { default?: string, description?: string } },
|
|
606
|
+
steps: [Step],
|
|
607
|
+
}
|
|
608
|
+
```
|
|
609
|
+
|
|
610
|
+
### 14.1 Step
|
|
611
|
+
|
|
612
|
+
```js
|
|
613
|
+
// 发送并可选等待/回读(v2 的 batch step,新增 capture)
|
|
614
|
+
{ send: string, enter?: boolean, waitFor?: { pattern?, idleMs?, timeoutMs? },
|
|
615
|
+
waitMs?: number, read?: 'delta'|'screen'|'none', maxLines?: number, capture?: string }
|
|
616
|
+
|
|
617
|
+
{ delay: number } // 毫秒,>0
|
|
618
|
+
{ set: string, value: string } // 变量名, 值(支持 {{var}})
|
|
619
|
+
{ log: string } // 追加一段人类可读输出
|
|
620
|
+
{ expect: Condition, onFail?: 'stop'|'continue', capture?: string } // 断言
|
|
621
|
+
{ if: Condition, then: Step[], else?: Step[] }
|
|
622
|
+
{ loop:
|
|
623
|
+
{ count?: number, while?: Condition, until?: Condition, maxIterations?: number },
|
|
624
|
+
steps: Step[] }
|
|
625
|
+
```
|
|
626
|
+
|
|
627
|
+
条件(Condition):
|
|
628
|
+
|
|
629
|
+
```js
|
|
630
|
+
{ always: true }
|
|
631
|
+
{ match: string } // 正则,匹配"自上次检查点以来的输出"
|
|
632
|
+
{ contains: string } // 纯文本包含
|
|
633
|
+
{ variable: string, equals?: string, notEquals?: string, contains?: string, matches?: string }
|
|
634
|
+
{ not: Condition }
|
|
635
|
+
{ all: Condition[] } | { any: Condition[] }
|
|
636
|
+
```
|
|
637
|
+
|
|
638
|
+
语义:
|
|
639
|
+
|
|
640
|
+
- **检查点(条件窗口)**:每个 target 维护一个"条件检查点"。条件与 `expect` 求值的文本是
|
|
641
|
+
"自上次**条件求值**以来的输出",因此:
|
|
642
|
+
- `send` / `wait` / `delay` / `set` / `log` **不**推进条件检查点;
|
|
643
|
+
- 只有求值 `if` / `loop.while` / `loop.until` / `expect` 才把检查点推进到当前末尾
|
|
644
|
+
(同一段输出不会被连续两个条件重复匹配);
|
|
645
|
+
- 于是"发送 → 立刻 `if {match}` / `expect`"能正确看到刚产生的输出,这是最常见的写法;
|
|
646
|
+
- 条件窗口取保留尾部并受读取上限约束(默认 8 KiB),不会无界增长。
|
|
647
|
+
- **模板**:`{{var}}` 在 `send`、`log`、`set.value`、`expect`/条件里的字符串中替换;
|
|
648
|
+
未知变量保留原文(不报错),但 `set` 的变量名必须匹配 `[A-Za-z_][A-Za-z0-9_]{0,31}`。
|
|
649
|
+
- **loop**:`count` 固定次数;`while` 每次迭代前求值;`until` 每次迭代后求值(真则退出);
|
|
650
|
+
`maxIterations` 默认 100、上限 1000;三者至少给一个(否则 `BAD_SCRIPT`)。
|
|
651
|
+
- **expect** 失败:`onFail: 'stop'`(默认)中止该 target;`continue` 记一条失败步骤后继续。
|
|
652
|
+
- 所有 `send` 仍然走 `registry.write(..., 'ai')`,权限拒绝即该步失败。
|
|
653
|
+
- 进度事件:`onStep({ sessionId, stepIndex, depth, kind, ok, text?, error?, path })`,
|
|
654
|
+
`path` 形如 `"3"`、`"3.2"`(嵌套块内),供面板缩进显示。
|
|
655
|
+
|
|
656
|
+
### 14.2 上限(硬约束,超出即 `BAD_SCRIPT` 或运行期截断)
|
|
657
|
+
|
|
658
|
+
| 项 | 上限 |
|
|
659
|
+
| --- | --- |
|
|
660
|
+
| 顶层 + 嵌套步骤总数 | 500 |
|
|
661
|
+
| 嵌套深度 | 5 |
|
|
662
|
+
| 单次 loop 迭代 | 1000(默认 100) |
|
|
663
|
+
| 变量个数 | 50 |
|
|
664
|
+
| 单变量值长度 | 8 KiB |
|
|
665
|
+
| 整个脚本时长 | 600000 ms(可由调用方调小) |
|
|
666
|
+
| 单步回读文本 | 8192 字节(沿用) |
|
|
667
|
+
|
|
668
|
+
### 14.3 API
|
|
669
|
+
|
|
670
|
+
```js
|
|
671
|
+
export function normalizeScriptProgram(steps: unknown): Step[] // 结构校验 + 上限
|
|
672
|
+
export function renderTemplates(value: string, variables: Record<string,string>): string
|
|
673
|
+
export async function runScript(registry, definition, options): Promise<ScriptRunResult>
|
|
674
|
+
// options: { params?, targets: string[], stopOnError?, maxTotalMs?, parallel?, onStep?, sleep?, now? }
|
|
675
|
+
// ScriptRunResult:
|
|
676
|
+
// {
|
|
677
|
+
// ok: boolean, timedOut: boolean, label?: string,
|
|
678
|
+
// runs: [{ sessionId, ok, steps: StepResult[], stoppedAt? }],
|
|
679
|
+
// variables: Record<string, string>, // 结束时(各 target 合并后的最后一个)
|
|
680
|
+
// logs: string[],
|
|
681
|
+
// }
|
|
682
|
+
// StepResult: { index, depth, path, kind, ok, matched?, text?, error?, code? }
|
|
683
|
+
```
|
|
684
|
+
|
|
685
|
+
`ScriptStore.save` 用 `normalizeScriptProgram` 校验 `steps`(不再只接受扁平 batch 步骤),
|
|
686
|
+
并继续拒绝 `password`/`privateKey`/`passphrase` 字段;`ScriptSummary` 增加 `folder`。
|
|
687
|
+
|
|
688
|
+
`aiterm_script_run` 改为调用 `runScript`;`aiterm_batch` 仍然只接受扁平步骤
|
|
689
|
+
(`normalizeSteps` 不变),两者共用 `registry` 的写入/等待/读取原语。
|
|
690
|
+
|
|
691
|
+
### 14.4 工具面增补
|
|
692
|
+
|
|
693
|
+
| 工具 | 作用 |
|
|
694
|
+
|---|---|
|
|
695
|
+
| `aiterm_script_save` | 保存/覆盖脚本(`{ script }`,AI 可用;删除仍仅限人) |
|
|
696
|
+
| `aiterm_script_list` | 增加 `folder` 字段展示 |
|
|
697
|
+
|
|
698
|
+
### 14.5 浏览器侧脚本 RPC
|
|
699
|
+
|
|
700
|
+
| method | params | result |
|
|
701
|
+
|---|---|---|
|
|
702
|
+
| `scripts.list` | `{}` | `{ scripts: ScriptSummary[] }`(含 `folder`、`stepCount`) |
|
|
703
|
+
| `scripts.get` | `{ name }` | `{ script: ScriptDefinition }`(**含 steps**,编辑器加载用;缺失 404) |
|
|
704
|
+
| `scripts.save` | `{ script }` | `{ script: ScriptSummary }`(human;AI 走工具) |
|
|
705
|
+
| `scripts.delete` | `{ name }` | `{ ok: boolean }`(human only) |
|
|
706
|
+
| `scripts.run` | `{ name, params?, sessionId?\|targets?, stopOnError?, maxTotalMs?, parallel? }` | `{ result: ScriptRunResult }` |
|
|
707
|
+
|
|
708
|
+
`ScriptSummary.stepCount` 统计**含嵌套**在内的步骤总数(`then`/`else`/`loop.steps` 递归计数),
|
|
709
|
+
用于面板显示"这个脚本有多大"。
|
|
710
|
+
|
|
711
|
+
---
|
|
712
|
+
|
|
713
|
+
# v4 增补:会话中断与重连
|
|
714
|
+
|
|
715
|
+
## 15. 会话生命周期
|
|
716
|
+
|
|
717
|
+
状态机(`SessionInfo.state`):
|
|
718
|
+
|
|
719
|
+
```
|
|
720
|
+
connecting ──ok──> open ──(user disconnect / remote close / network drop)──> disconnected
|
|
721
|
+
│ ▲ │
|
|
722
|
+
└──fail──> failed└────────────────── reconnect ─────────────────────────────┘
|
|
723
|
+
open/disconnected ──(user close)──> closed(从列表移除)
|
|
724
|
+
```
|
|
725
|
+
|
|
726
|
+
关键语义:
|
|
727
|
+
|
|
728
|
+
- **`disconnected` 是"可恢复"的终态**:会话留在列表里,`id`、`title`、`aiAccess`、历史输出、审计全部保留;
|
|
729
|
+
传输已关闭,不能读写(写入返回 `NOT_CONNECTED`)。
|
|
730
|
+
- **远端意外断开不再删除会话**:`onClose` 只要不是用户主动 `close`、且曾经 `open` 过,就进入 `disconnected`
|
|
731
|
+
并记录 `closeReason` / `disconnectedAt`。这修掉了"网络抖一下会话就没了"的行为。
|
|
732
|
+
- **`reconnect` 复用同一个 id**:不新建 session,历史/权限/审计继续累积;`generation` 自增。
|
|
733
|
+
- **重连会重建屏幕**(远端是新的 shell):服务端重置 `Screen`,并广播
|
|
734
|
+
`{ "type": "reset", "session": SessionInfo, "reason": string }`;客户端收到后清空 xterm 再继续接收 `data`。
|
|
735
|
+
输出日志(`OutputLog`)与历史**不清空**,`cursor` 继续单调增长,旧游标仍然有效。
|
|
736
|
+
- 重连丢失控制权:`lockOwner` 清空(连接已断,锁无意义),`aiAccess` 保留。
|
|
737
|
+
- 权限门禁不变:`disconnected` 状态下读返回空文本、写返回 `NOT_CONNECTED`。
|
|
738
|
+
|
|
739
|
+
## 16. 认证材料与重连
|
|
740
|
+
|
|
741
|
+
重连需要认证信息,但插件**不持久化明文口令**:
|
|
742
|
+
|
|
743
|
+
- 会话来自保存的配置(`profileId`)→ 重连时通过 `ProfileStore.connectionFor(profileId)` 重新解析(推荐路径)。
|
|
744
|
+
- 会话是 ad-hoc 且带口令/私钥 → 这些材料**仅保留在 Host 进程内存**(`session.auth`),
|
|
745
|
+
进程重启即消失;从不写入磁盘、日志、工具结果或 SSE,`SessionInfo` 也不含它。
|
|
746
|
+
- `agent` / `none` 认证无需材料。
|
|
747
|
+
- 若既无 profile 也无内存材料(例如重启后、或当初由 AI 用 agent 建立)→ 重连返回
|
|
748
|
+
`coded('RECONNECT_NO_CREDENTIALS')`,提示用户用配置重连。
|
|
749
|
+
|
|
750
|
+
## 17. RPC 与工具
|
|
751
|
+
|
|
752
|
+
| method | params | result |
|
|
753
|
+
|---|---|---|
|
|
754
|
+
| `sessions.disconnect` | `{ id, reason? }` | `{ session }`(state=`disconnected`) |
|
|
755
|
+
| `sessions.reconnect` | `{ id, cols?, rows? }` | `{ session }`(state=`open` 或 `failed`;失败不抛,带 `error`) |
|
|
756
|
+
|
|
757
|
+
- `sessions.close` 语义不变(终止并从列表移除)。
|
|
758
|
+
- 两者均**人类可用**;模型也可通过工具触发(不涉及提升权限)。
|
|
759
|
+
|
|
760
|
+
工具面新增:
|
|
761
|
+
|
|
762
|
+
| 工具 | 作用 |
|
|
763
|
+
|---|---|
|
|
764
|
+
| `aiterm_disconnect` | 断开但保留会话(可重连) |
|
|
765
|
+
| `aiterm_reconnect` | 重连该会话(同一 id,历史保留) |
|
|
766
|
+
|
|
767
|
+
`SessionInfo` 新增字段:
|
|
768
|
+
|
|
769
|
+
```js
|
|
770
|
+
{
|
|
771
|
+
...既有字段,
|
|
772
|
+
generation: number, // 每次成功 (重)连 +1;客户端据此判断是否需要清屏
|
|
773
|
+
disconnectedAt?: number, // 最近一次断开时间
|
|
774
|
+
closeReason?: string, // 断开原因('user disconnect' / 'connection closed' / 错误摘要)
|
|
775
|
+
reconnecting?: boolean, // 重连进行中
|
|
776
|
+
}
|
|
777
|
+
```
|
|
778
|
+
|
|
779
|
+
## 18. 资源上限与配置
|
|
780
|
+
|
|
781
|
+
```yaml
|
|
782
|
+
maxDetachedSessions: 20 # 同时保留的 disconnected 会话上限,超出按 disconnectedAt 最旧修剪
|
|
783
|
+
autoReconnect: false # 意外断开时是否自动重连
|
|
784
|
+
autoReconnectAttempts: 3 # 自动重连次数上限(autoReconnect=true 时)
|
|
785
|
+
autoReconnectDelayMs: 2000 # 首次重试延迟,指数退避到 30s
|
|
786
|
+
```
|
|
787
|
+
|
|
788
|
+
`maxSessions` 只统计 `connecting` / `open`(断开的不占连接名额),但仍受 `maxDetachedSessions` 约束。
|
|
789
|
+
|
|
790
|
+
SSE 新增帧(全局与单会话流都发):
|
|
791
|
+
|
|
792
|
+
```json
|
|
793
|
+
{ "type": "reset", "session": SessionInfo, "reason": "user disconnect" }
|
|
794
|
+
```
|