dsh-aiterm 0.5.1 → 0.5.13

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.
@@ -242,6 +242,7 @@ async function invoke(plugin, name, params) {
242
242
  case 'audit.list':
243
243
  return {
244
244
  entries: registry.audit({
245
+ actor: 'human',
245
246
  sessionId: typeof params.id === 'string' ? params.id : undefined,
246
247
  limit: params.limit,
247
248
  }),
@@ -260,12 +261,22 @@ async function invoke(plugin, name, params) {
260
261
  changedOnly: params.changedOnly === true,
261
262
  maxLines: params.maxLines,
262
263
  })
263
- case 'history.sessions':
264
- return { sessions: await registry.historySessions({ limit: params.limit, since: params.since, until: params.until }) }
264
+ case 'history.sessions': {
265
+ const page = await registry.historySessionsPage({
266
+ actor: 'human',
267
+ limit: params.limit,
268
+ offset: params.offset,
269
+ snapshot: params.snapshot,
270
+ since: params.since,
271
+ until: params.until,
272
+ })
273
+ return page
274
+ }
265
275
  case 'history.query':
266
276
  return registry.historyQuery({
267
277
  actor: 'human',
268
278
  sessionId: typeof params.sessionId === 'string' ? params.sessionId : undefined,
279
+ historyId: typeof params.historyId === 'string' ? params.historyId : undefined,
269
280
  since: params.since,
270
281
  until: params.until,
271
282
  search: params.search,
@@ -274,9 +285,40 @@ async function invoke(plugin, name, params) {
274
285
  maxBytes: params.maxBytes,
275
286
  limit: params.limit,
276
287
  })
288
+ case 'history.legacy.sessions': {
289
+ const page = await registry.legacyHistorySessionsPage({
290
+ actor: 'human',
291
+ limit: params.limit,
292
+ offset: params.offset,
293
+ snapshot: params.snapshot,
294
+ since: params.since,
295
+ until: params.until,
296
+ })
297
+ return page
298
+ }
299
+ case 'history.legacy.query':
300
+ return registry.legacyHistoryQuery({
301
+ actor: 'human',
302
+ sessionId: typeof params.sessionId === 'string' ? params.sessionId : undefined,
303
+ since: params.since,
304
+ until: params.until,
305
+ search: params.search,
306
+ context: params.context,
307
+ maxMatches: params.maxMatches,
308
+ maxBytes: params.maxBytes,
309
+ })
310
+ case 'history.legacy.export':
311
+ return registry.legacyHistoryExport({
312
+ actor: 'human',
313
+ sessionId: typeof params.sessionId === 'string' ? params.sessionId : undefined,
314
+ since: params.since,
315
+ until: params.until,
316
+ })
277
317
  case 'history.export':
278
318
  return registry.exportHistory({
319
+ actor: 'human',
279
320
  sessionId: typeof params.sessionId === 'string' ? params.sessionId : undefined,
321
+ historyId: typeof params.historyId === 'string' ? params.historyId : undefined,
280
322
  all: params.all === true,
281
323
  since: params.since,
282
324
  until: params.until,
@@ -287,6 +329,7 @@ async function invoke(plugin, name, params) {
287
329
  return autoLog(registry).set({
288
330
  enabled: typeof params.enabled === 'boolean' ? params.enabled : undefined,
289
331
  dir: params.dir,
332
+ confirmLegacy: params.confirmLegacy === true,
290
333
  })
291
334
  case 'scripts.list':
292
335
  return { scripts: await requireScripts(plugin).list() }
package/lib/host/tools.js CHANGED
@@ -15,6 +15,7 @@ import { AsyncLocalStorage } from 'node:async_hooks'
15
15
 
16
16
  import { coded, jsonSafe } from './util.js'
17
17
  import { normalizeSteps, runBatch } from './batch.js'
18
+ import { createDisclosure, DISCLOSURE_GROUPS } from './disclosure.js'
18
19
  import { normalizeOwner, ownerScopedRegistry } from './registry.js'
19
20
  import { runScript } from './script-lang.js'
20
21
 
@@ -150,6 +151,99 @@ const AUDIT_ENTRY_SCHEMA = {
150
151
  required: ['at', 'sessionId', 'source', 'action', 'detail'],
151
152
  }
152
153
 
154
+ /** Name of the always-resident progressive-mode discovery entry. */
155
+ export const DISCOVER_TOOL_NAME = 'aiterm_discover'
156
+
157
+ /**
158
+ * Model-facing description of the discovery entry.
159
+ *
160
+ * In `progressive` mode this description is the single resident home of the
161
+ * disclosure and session-control rules (`lib/host/prompt.js` registers no
162
+ * system-prompt section there), so the request carries that guidance once
163
+ * instead of twice. It names only groups, never another tool: a tool this
164
+ * Agent cannot see must not be leaked here.
165
+ */
166
+ export const DISCOVER_TOOL_DESCRIPTION =
167
+ 'Discover the SSH/Telnet toolset. Call with no arguments to list the available groups, the tools this Agent may see, and the groups already expanded; call again with one group (session, history, automation, management) to expand it. Begin with the session group: the other groups need an existing session id. Expansion only reveals schemas, takes effect on the next model step, and never grants permission. Each session keeps its own AI permission - read-only (只读) never sends input, write-only (只写) never reads output, read-write (读写) allows both - and only the user can change it, so report a refusal instead of retrying or working around it. While you send input you hold control of the session and the user cannot type; release control as soon as a multi-step operation ends. Read the screen before and after a command, send a newline with a trailing "\\r" (or enter:true), and never assume a command finished without checking its output.'
168
+
169
+ /** Group names accepted by the discovery entry. */
170
+ const DISCLOSURE_GROUP_NAMES = Object.freeze(Object.keys(DISCLOSURE_GROUPS))
171
+
172
+ /**
173
+ * Wire shape of a discovery/expansion result.
174
+ *
175
+ * It accepts both the success payload and every fail-closed refusal produced by
176
+ * the Task 1 controller; `additionalProperties: false` keeps hostile or
177
+ * accidental extras from ever reaching the model.
178
+ */
179
+ const DISCOVERY_OUTPUT_SCHEMA = {
180
+ type: 'object',
181
+ additionalProperties: false,
182
+ properties: {
183
+ ok: { type: 'boolean' },
184
+ mode: { type: 'string', enum: ['full', 'progressive'] },
185
+ groups: {
186
+ type: 'array',
187
+ items: {
188
+ type: 'object',
189
+ additionalProperties: false,
190
+ properties: {
191
+ group: { type: 'string' },
192
+ tools: { type: 'array', items: { type: 'string' } },
193
+ },
194
+ required: ['group', 'tools'],
195
+ },
196
+ },
197
+ expanded: { type: 'array', items: { type: 'string' } },
198
+ visible: { type: 'array', items: { type: 'string' } },
199
+ dependencies: {
200
+ type: 'array',
201
+ items: {
202
+ type: 'object',
203
+ additionalProperties: false,
204
+ properties: {
205
+ group: { type: 'string' },
206
+ requires: { type: 'array', items: { type: 'string' } },
207
+ hint: { type: 'string' },
208
+ },
209
+ required: ['group', 'requires', 'hint'],
210
+ },
211
+ },
212
+ hints: { type: 'array', items: { type: 'string' } },
213
+ nextStep: { type: 'string' },
214
+ error: { type: 'string' },
215
+ group: { type: 'string' },
216
+ },
217
+ required: ['ok', 'mode', 'groups', 'expanded', 'visible', 'dependencies', 'hints', 'nextStep'],
218
+ }
219
+
220
+ /**
221
+ * Render a discovery or expansion result as compact text.
222
+ * @param {Record<string, any>} value JSON-safe result from the controller.
223
+ * @returns {string} model-facing text.
224
+ */
225
+ function renderDiscovery(value) {
226
+ const lines = []
227
+ if (value.ok === false) {
228
+ lines.push(`Tool discovery refused (${String(value.error)}).`)
229
+ } else {
230
+ lines.push(`Tool disclosure mode: ${String(value.mode)}.`)
231
+ for (const { group, tools: members } of value.groups) {
232
+ const state = value.expanded.includes(group) ? ' [expanded]' : ''
233
+ lines.push(`${group}${state}${members.length === 0 ? ' — no tools are available to this Agent' : ''}`)
234
+ for (const name of members) lines.push(` ${name}`)
235
+ }
236
+ if (typeof value.group === 'string') {
237
+ lines.push('', value.mode === 'progressive'
238
+ ? `Expanded "${value.group}"; its tools become callable on the next model step.`
239
+ : `Full mode already exposes every tool; "${value.group}" needs no expansion.`)
240
+ }
241
+ }
242
+ if (typeof value.nextStep === 'string' && value.nextStep.length > 0) lines.push('', value.nextStep)
243
+ for (const hint of value.hints ?? []) lines.push(`- ${hint}`)
244
+ return lines.join('\n')
245
+ }
246
+
153
247
  /**
154
248
  * One text content block.
155
249
  * @param {string} text content.
@@ -245,12 +339,38 @@ function sleep(ms) {
245
339
  * @returns {void}
246
340
  */
247
341
  export function registerTools(ctx, plugin) {
342
+ // `resolveConfig` guarantees only the exact `progressive` value enables the
343
+ // new behaviour; everything else (including a direct caller's `{}`) keeps the
344
+ // historical unconditional registration untouched, including its lifecycle.
345
+ const progressive = plugin?.config?.toolDisclosure === 'progressive'
346
+ const disclosure = progressive ? createDisclosure({ mode: 'progressive', tools: ctx.tools }) : undefined
347
+
348
+ if (disclosure !== undefined) {
349
+ // Agent disposal is the only reliable end-of-life signal for the per-Agent
350
+ // expansion state. `ctx.on` is owned by this plugin's fiber, so unloading
351
+ // the plugin also removes the listener; the effect below additionally
352
+ // clears the controller so late conditions fail closed during teardown.
353
+ if (typeof ctx.on === 'function') {
354
+ ctx.on('agent/disposed', ({ agent }) => {
355
+ disclosure.forget(agent)
356
+ })
357
+ }
358
+ ctx.effect(() => () => disclosure.dispose(), 'aiterm: tool disclosure')
359
+ }
360
+
248
361
  /**
249
- * Register one tool.
362
+ * Register one original business tool.
250
363
  *
251
364
  * Tool results are validated as lossless JSON before they reach the model, so
252
365
  * every payload is normalized (absent optional fields dropped, non-finite
253
366
  * numbers nulled) on the way out.
367
+ *
368
+ * In progressive mode only, the original registration gains a step-time
369
+ * condition reading the invoking Agent from the `ToolActivationContext`. The
370
+ * condition is side-effect free, synchronous, and catches every failure
371
+ * (including a hostile `agent.id` getter) so a bad caller cannot fail step
372
+ * preparation or widen visibility. No scoped tool is registered, so existing
373
+ * restrictions and scope-local definitions keep their exact behaviour.
254
374
  * @param {Record<string, any>} definition tool definition.
255
375
  */
256
376
  const register = (definition) => {
@@ -265,6 +385,17 @@ export function registerTools(ctx, plugin) {
265
385
  return safe === undefined ? null : safe
266
386
  },
267
387
  }
388
+ if (progressive) {
389
+ const when = (context) => {
390
+ try {
391
+ return disclosure.isVisible(context?.agent, definition.name)
392
+ } catch {
393
+ return false
394
+ }
395
+ }
396
+ ctx.effect(() => ctx.tools.register(guarded, { when }), `aiterm: tool ${definition.name}`)
397
+ return
398
+ }
268
399
  ctx.effect(() => ctx.tools.register(guarded), `aiterm: tool ${definition.name}`)
269
400
  }
270
401
 
@@ -296,17 +427,17 @@ export function registerTools(ctx, plugin) {
296
427
  register({
297
428
  name: 'aiterm_connect',
298
429
  description:
299
- 'Open a new SSH or Telnet session in the visible SSH/Telnet panel. Prefer connecting through a saved profile (profileId) — saved passwords and private keys are read by the Host and never exposed to you. Ad-hoc connections may only use agent/none authentication; do not ask the user for a password. The session starts with the deployment default AI permission and the user can change it at any time.',
430
+ 'Open a new SSH or Telnet session in the visible SSH/Telnet panel. Prefer connecting through a saved profile (profileId) — saved passwords and private keys are read by the Host and never exposed to you. With profileId, pass ONLY profileId (plus title/cols/rows): transport/host/port/username/authType overrides are rejected so saved credentials cannot be redirected. Ad-hoc connections may only use agent/none authentication; do not ask the user for a password. The session starts with the deployment default AI permission and the user can change it at any time.',
300
431
  parameters: {
301
432
  type: 'object',
302
433
  additionalProperties: false,
303
434
  properties: {
304
435
  profileId: { type: 'string', description: 'Saved profile id from the panel (recommended).' },
305
- transport: { type: 'string', enum: ['ssh', 'telnet'], description: 'Ad-hoc connection transport (ignored with profileId).' },
306
- host: { type: 'string', description: 'Ad-hoc host name or IP (ignored with profileId).' },
307
- port: { type: 'integer', description: 'Ad-hoc port (default 22 for SSH, 23 for Telnet).' },
308
- username: { type: 'string', description: 'Ad-hoc SSH username.' },
309
- authType: { type: 'string', enum: ['agent', 'none'], description: 'Ad-hoc SSH auth; password/key connections must use a saved profile.' },
436
+ transport: { type: 'string', enum: ['ssh', 'telnet'], description: 'Ad-hoc connection transport; cannot be combined with profileId (AI calls are rejected).' },
437
+ host: { type: 'string', description: 'Ad-hoc host name or IP; cannot be combined with profileId (AI calls are rejected).' },
438
+ port: { type: 'integer', description: 'Ad-hoc port (default 22 for SSH, 23 for Telnet); cannot be combined with profileId.' },
439
+ username: { type: 'string', description: 'Ad-hoc SSH username; cannot be combined with profileId.' },
440
+ authType: { type: 'string', enum: ['agent', 'none'], description: 'Ad-hoc SSH auth; cannot be combined with profileId. Password/key connections must use a saved profile.' },
310
441
  title: { type: 'string', description: 'Optional display title.' },
311
442
  cols: { type: 'integer', description: 'Terminal columns (default 100).' },
312
443
  rows: { type: 'integer', description: 'Terminal rows (default 30).' },
@@ -591,12 +722,16 @@ export function registerTools(ctx, plugin) {
591
722
  register({
592
723
  name: 'aiterm_history',
593
724
  description:
594
- 'Search or read a session\'s output history with timestamps, including sessions that already closed (history is kept on disk for the configured retention window). Omit sessionId to list recent sessions (live and past) with sizes and time ranges. With sessionId: pass search (regex or text) to get matching lines with timestamps and context, or since/until alone to read that time window. Time values accept epoch milliseconds, ISO timestamps, or relative amounts like "10m", "2h", "90s". Cheapest way to answer "what happened at 16:02" without re-reading screens.',
725
+ 'Search or read a session\'s output history with timestamps, including sessions that already closed (history is kept on disk for the configured retention window). Omit sessionId to list recent sessions (live and past) with sizes and time ranges; page with limit/offset and pass the returned snapshot back. If history changed between pages (including a live close), stale:true is returned instead of silently skipping rows. With sessionId: pass search (regex or text) to get matching lines with timestamps and context, or since/until alone to read that time window. Time values accept epoch milliseconds, ISO timestamps, or relative amounts like "10m", "2h", "90s". Cheapest way to answer "what happened at 16:02" without re-reading screens.',
595
726
  parameters: {
596
727
  type: 'object',
597
728
  additionalProperties: false,
598
729
  properties: {
599
730
  sessionId: { type: 'string', description: 'Session id; omit to list sessions instead.' },
731
+ historyId: {
732
+ type: 'string',
733
+ description: 'Optional exact incarnation address from the session list. Use it when several incarnations share one logical session id; required to address an older one.',
734
+ },
600
735
  since: { type: 'string', description: 'Start time (ISO, epoch ms, or relative like "10m").' },
601
736
  until: { type: 'string', description: 'End time.' },
602
737
  search: { type: 'string', description: 'Regular expression or plain text to find (case-insensitive).' },
@@ -604,6 +739,8 @@ export function registerTools(ctx, plugin) {
604
739
  maxMatches: { type: 'integer', description: 'Maximum matches (default 20).' },
605
740
  maxBytes: { type: 'integer', description: 'Byte cap for a plain time-window read.' },
606
741
  limit: { type: 'integer', description: 'Maximum sessions to list when sessionId is omitted.' },
742
+ offset: { type: 'integer', description: 'Offset for the session list (paging); truncated/total are returned.' },
743
+ snapshot: { type: 'string', description: 'Snapshot token from the previous list page. If history changed, stale:true is returned instead of silently skipping rows.' },
607
744
  },
608
745
  },
609
746
  output: {
@@ -628,6 +765,7 @@ export function registerTools(ctx, plugin) {
628
765
  bytes: { type: 'number' },
629
766
  lastTs: { type: 'number' },
630
767
  live: { type: 'boolean' },
768
+ historyId: { type: 'string' },
631
769
  },
632
770
  required: ['id', 'title', 'transport', 'host'],
633
771
  },
@@ -649,6 +787,10 @@ export function registerTools(ctx, plugin) {
649
787
  },
650
788
  text: { type: 'string' },
651
789
  truncated: { type: 'boolean' },
790
+ total: { type: 'integer' },
791
+ snapshot: { type: 'string' },
792
+ stale: { type: 'boolean' },
793
+ limitReached: { type: 'boolean' },
652
794
  scannedBytes: { type: 'number' },
653
795
  since: { type: 'number' },
654
796
  complete: { type: 'boolean' },
@@ -667,6 +809,7 @@ export function registerTools(ctx, plugin) {
667
809
  bytes: { type: 'number' },
668
810
  lastTs: { type: 'number' },
669
811
  live: { type: 'boolean' },
812
+ historyId: { type: 'string' },
670
813
  },
671
814
  required: ['id', 'title', 'transport', 'host'],
672
815
  },
@@ -675,13 +818,34 @@ export function registerTools(ctx, plugin) {
675
818
  },
676
819
  render: (args, value) => {
677
820
  if (Array.isArray(value.sessions)) {
678
- if (value.sessions.length === 0) return textContent('No session history is available yet.')
821
+ const snapshot = typeof value.snapshot === 'string' && value.snapshot.length > 0
822
+ ? `\nsnapshot: ${value.snapshot}`
823
+ : ''
824
+ const offset = Number.isInteger(args.offset) ? args.offset : 0
825
+ if (value.stale === true) {
826
+ return textContent(`History changed while paging; restart from the first page (call again with offset 0 and no snapshot) or narrow the time window.${snapshot}`)
827
+ }
828
+ if (value.sessions.length === 0) {
829
+ return textContent(value.limitReached === true
830
+ ? `No more rows can be paged at this server source limit; total may be overestimated for legacy sources; narrow the time window.${snapshot}`
831
+ : `No session history is available yet.${snapshot}`)
832
+ }
679
833
  const lines = value.sessions.map((entry) => {
680
834
  const when = new Date(entry.createdAt).toISOString().slice(11, 19)
681
835
  const end = entry.closedAt === undefined ? 'live' : new Date(entry.closedAt).toISOString().slice(11, 19)
682
- return `${entry.id} ${entry.title} [${entry.transport} ${entry.host}:${entry.port}] ${when}→${end} ${entry.bytes}B`
836
+ const address = typeof entry.historyId === 'string' && entry.historyId.length > 0 ? ` historyId=${entry.historyId}` : ''
837
+ return `${entry.id}${address} ${entry.title} [${entry.transport} ${entry.host}:${entry.port}] ${when}→${end} ${entry.bytes}B`
683
838
  })
684
- return textContent(lines.join('\n'))
839
+ const total = Number.isInteger(value.total) ? value.total : value.sessions.length
840
+ const footer = value.limitReached === true
841
+ ? `\n\n[showing ${value.sessions.length} of ${total} — server source limit reached; total may be overestimated for legacy sources; narrow the time window]`
842
+ : (value.truncated === true
843
+ ? `\n\n[showing ${value.sessions.length} of ${total} — more history exists; raise limit, use offset, or narrow the window]`
844
+ : '')
845
+ const next = value.limitReached === true || value.truncated !== true
846
+ ? ''
847
+ : `\nTo page, call aiterm_history again with offset=${offset + value.sessions.length}${snapshot.length > 0 ? ' and the snapshot above' : ''}.`
848
+ return textContent(`${lines.join('\n')}${footer}${snapshot}${next}`)
685
849
  }
686
850
  if (Array.isArray(value.matches)) {
687
851
  if (value.matches.length === 0) return textContent(`No match (scanned ${value.scannedBytes} bytes).`)
@@ -704,6 +868,7 @@ export function registerTools(ctx, plugin) {
704
868
  const registry = requireRegistry(plugin)
705
869
  return registry.historyQuery({
706
870
  sessionId: args.sessionId,
871
+ historyId: args.historyId,
707
872
  since: args.since,
708
873
  until: args.until,
709
874
  search: args.search,
@@ -711,6 +876,8 @@ export function registerTools(ctx, plugin) {
711
876
  maxMatches: args.maxMatches,
712
877
  maxBytes: args.maxBytes,
713
878
  limit: args.limit,
879
+ offset: args.offset,
880
+ snapshot: args.snapshot,
714
881
  })
715
882
  },
716
883
  })
@@ -1172,13 +1339,17 @@ export function registerTools(ctx, plugin) {
1172
1339
  register({
1173
1340
  name: 'aiterm_export',
1174
1341
  description:
1175
- 'Export a session\'s stored output history (live or already closed) as a human-readable text log file on the Host. Each line is "<ISO timestamp> <output line>", after a header with transport/host/port/username/title/start. Use all:true to export every known session, or sessionId for one (omitted: the only session). Returns the absolute paths with byte and line counts so the user can pick the files up from the Host file panel. Time values accept epoch milliseconds, ISO timestamps, or relative amounts like "10m".',
1342
+ 'Export stored output history for sessions owned by the current conversation (live or already closed) as human-readable text log files on the Host. all:true exports every readable incarnation — including several incarnations that share one logical session id — and returns a skipped list for unreadable/missing sources; a write-only closed incarnation is reported as skipped rather than leaked. Pass historyId to export one exact incarnation. Each line is "<ISO timestamp> <output line>", after a header with transport/host/port/username/title/start. Returns absolute paths with byte and line counts. Time values accept epoch milliseconds, ISO timestamps, or relative amounts like "10m".',
1176
1343
  parameters: {
1177
1344
  type: 'object',
1178
1345
  additionalProperties: false,
1179
1346
  properties: {
1180
1347
  sessionId: { type: 'string', description: 'Session to export; omit to use the only session.' },
1181
- all: { type: 'boolean', description: 'Export every session, including already closed ones.' },
1348
+ historyId: {
1349
+ type: 'string',
1350
+ description: 'Optional exact incarnation address. Use it to export an older incarnation that shares a logical session id.',
1351
+ },
1352
+ all: { type: 'boolean', description: 'Export every session owned by this conversation, including already closed ones.' },
1182
1353
  since: { type: 'string', description: 'Start time (ISO, epoch ms, or relative like "10m").' },
1183
1354
  until: { type: 'string', description: 'End time (ISO, epoch ms, or relative like "2h").' },
1184
1355
  },
@@ -1196,6 +1367,7 @@ export function registerTools(ctx, plugin) {
1196
1367
  additionalProperties: false,
1197
1368
  properties: {
1198
1369
  sessionId: { type: 'string' },
1370
+ historyId: { type: 'string' },
1199
1371
  path: { type: 'string' },
1200
1372
  bytes: { type: 'integer' },
1201
1373
  lines: { type: 'integer' },
@@ -1203,21 +1375,58 @@ export function registerTools(ctx, plugin) {
1203
1375
  required: ['sessionId', 'path', 'bytes', 'lines'],
1204
1376
  },
1205
1377
  },
1378
+ skipped: {
1379
+ type: 'array',
1380
+ items: {
1381
+ type: 'object',
1382
+ additionalProperties: false,
1383
+ properties: {
1384
+ sessionId: { type: 'string' },
1385
+ historyId: { type: 'string' },
1386
+ code: { type: 'string' },
1387
+ message: { type: 'string' },
1388
+ count: { type: 'integer' },
1389
+ },
1390
+ required: ['sessionId', 'code', 'message'],
1391
+ },
1392
+ },
1393
+ omitted: {
1394
+ type: 'object',
1395
+ additionalProperties: false,
1396
+ properties: {
1397
+ count: { type: 'integer' },
1398
+ limit: { type: 'integer' },
1399
+ reason: { type: 'string' },
1400
+ },
1401
+ required: ['count', 'limit', 'reason'],
1402
+ },
1403
+ skippedTotal: { type: 'integer' },
1206
1404
  },
1207
- required: ['dir', 'files'],
1405
+ required: ['dir', 'files', 'skipped'],
1208
1406
  },
1209
1407
  render: (args, value) => {
1210
- if (!Array.isArray(value.files) || value.files.length === 0) {
1408
+ const files = Array.isArray(value.files) ? value.files : []
1409
+ const skipped = Array.isArray(value.skipped) ? value.skipped : []
1410
+ if (files.length === 0 && skipped.length === 0) {
1211
1411
  return textContent(`No history to export (checked ${value.dir}).`)
1212
1412
  }
1213
- const lines = value.files.map((file) => `${file.sessionId} ${file.bytes}B ${file.lines} lines ${file.path}`)
1214
- return textContent(`Exported ${value.files.length} log file(s) to ${value.dir}:\n${lines.join('\n')}`)
1413
+ const lines = files.map((file) => `${file.sessionId}${file.historyId ? ` (${file.historyId})` : ''} ${file.bytes}B ${file.lines} lines ${file.path}`)
1414
+ if (files.length === 0) {
1415
+ const skippedTotal = Number.isInteger(value.skippedTotal) ? value.skippedTotal : skipped.length
1416
+ const omitted = value.omitted ? `, ${value.omitted.count} incarnation(s) not attempted (${value.omitted.reason})` : ''
1417
+ return textContent(`No history file could be exported (checked ${value.dir}); ${skippedTotal} source(s) skipped${omitted}.`)
1418
+ }
1419
+ const skippedTotal = Number.isInteger(value.skippedTotal) ? value.skippedTotal : skipped.length
1420
+ const suffix = skippedTotal > 0 ? `\nSkipped ${skippedTotal} entry/entries (details: ${skipped.length}).` : ''
1421
+ const omitted = value.omitted ? `\n${value.omitted.count} incarnation(s) were not attempted (${value.omitted.reason}, limit ${value.omitted.limit}).` : ''
1422
+ return textContent(`Exported ${files.length} log file(s) to ${value.dir}:\n${lines.join('\n')}${suffix}${omitted}`)
1215
1423
  },
1216
1424
  },
1217
1425
  async execute(args) {
1218
1426
  const registry = requireRegistry(plugin)
1219
1427
  return registry.exportHistory({
1220
1428
  sessionId: args.sessionId,
1429
+ historyId: args.historyId,
1221
1430
  all: args.all === true,
1222
1431
  since: args.since,
1223
1432
  until: args.until,
@@ -1228,7 +1437,7 @@ export function registerTools(ctx, plugin) {
1228
1437
  register({
1229
1438
  name: 'aiterm_autolog',
1230
1439
  description:
1231
- 'Query or change automatic log-file writing. With no arguments it reports the current switch and directory. Off by default; when enabled, every session appends its live output to <dir>/<sessionId>.log with a header containing only transport/host/port/username/title (never credentials). The setting and directory persist across Host restarts.',
1440
+ 'Query automatic log-file writing. With no arguments it reports the current switch and directory. This is a host-wide privacy setting: only the human can change it from the history panel, so the AI can read the state but any attempt to enable/disable it or choose a directory is refused. Off by default; when enabled, every session appends its live output to <dir>/<sessionId>.log with a header containing only transport/host/port/username/title (never credentials). The setting and directory persist across Host restarts.',
1232
1441
  parameters: {
1233
1442
  type: 'object',
1234
1443
  additionalProperties: false,
@@ -1244,20 +1453,80 @@ export function registerTools(ctx, plugin) {
1244
1453
  properties: {
1245
1454
  enabled: { type: 'boolean' },
1246
1455
  dir: { type: 'string' },
1456
+ needsReview: { type: 'boolean' },
1247
1457
  },
1248
1458
  required: ['enabled', 'dir'],
1249
1459
  },
1250
- render: (args, value) =>
1251
- textContent(`Automatic log files: ${value.enabled ? 'enabled' : 'disabled'}\nDirectory: ${value.dir}`),
1460
+ render: (args, value) => {
1461
+ const review = value.needsReview === true
1462
+ ? '\nThis switch was enabled by an older version and is paused: only the human can confirm it in the history panel.'
1463
+ : ''
1464
+ return textContent(`Automatic log files: ${value.enabled ? 'enabled' : 'disabled'}\nDirectory: ${value.dir}${review}`)
1465
+ },
1252
1466
  },
1253
1467
  async execute(args) {
1254
1468
  const registry = requireRegistry(plugin)
1255
1469
  const autolog = registry.autolog
1256
1470
  if (autolog === undefined || autolog === null) throw new Error('automatic log files are not available in this build')
1257
- if (args.enabled === undefined && args.dir === undefined) return autolog.get()
1258
- return autolog.set({ enabled: typeof args.enabled === 'boolean' ? args.enabled : undefined, dir: args.dir })
1471
+ // The switch and directory are host-wide: enabling them makes every
1472
+ // session, including other owners' terminals, write plaintext output to a
1473
+ // path the AI chooses. That is a cross-owner disclosure primitive, so the
1474
+ // AI may read the state but only the human panel may change it.
1475
+ if (args.enabled !== undefined || args.dir !== undefined) {
1476
+ throw coded(
1477
+ 'HUMAN_ONLY',
1478
+ 'automatic log files are a host-wide privacy setting; only the human can change it from the history panel',
1479
+ 403,
1480
+ )
1481
+ }
1482
+ return autolog.get()
1259
1483
  },
1260
1484
  })
1485
+
1486
+ // The discovery entry is deliberately not part of any business group: it
1487
+ // never touches a terminal, is registered without a condition so it stays
1488
+ // resident in progressive mode, and exists only there (full mode keeps the
1489
+ // historical 21-tool surface).
1490
+ if (progressive) {
1491
+ const discoveryDefinition = {
1492
+ name: DISCOVER_TOOL_NAME,
1493
+ description: DISCOVER_TOOL_DESCRIPTION,
1494
+ parameters: {
1495
+ type: 'object',
1496
+ additionalProperties: false,
1497
+ properties: {
1498
+ group: {
1499
+ type: 'string',
1500
+ enum: DISCLOSURE_GROUP_NAMES,
1501
+ description: 'Group to expand; omit to only inspect the current disclosure state.',
1502
+ },
1503
+ },
1504
+ },
1505
+ output: {
1506
+ schema: DISCOVERY_OUTPUT_SCHEMA,
1507
+ render: (args, value) => textContent(renderDiscovery(value)),
1508
+ },
1509
+ async execute(args, exec) {
1510
+ const agent = exec?.agent
1511
+ if (args !== null && typeof args === 'object' && args.group !== undefined) {
1512
+ return disclosure.expand(agent, args.group)
1513
+ }
1514
+ return disclosure.discover(agent)
1515
+ },
1516
+ }
1517
+ const discoveryExecute = discoveryDefinition.execute
1518
+ const guardedDiscovery = {
1519
+ ...discoveryDefinition,
1520
+ async execute(args, exec) {
1521
+ // No terminal-owner binding: discovery never touches the session
1522
+ // registry, so it must work before any terminal exists.
1523
+ const value = await discoveryExecute(args, exec)
1524
+ const safe = jsonSafe(value)
1525
+ return safe === undefined ? null : safe
1526
+ },
1527
+ }
1528
+ ctx.effect(() => ctx.tools.register(guardedDiscovery), `aiterm: tool ${DISCOVER_TOOL_NAME}`)
1529
+ }
1261
1530
  }
1262
1531
 
1263
1532
  /** Wire shape of one batch run. */
package/lib/index.js CHANGED
@@ -115,8 +115,10 @@ export function apply(ctx, config) {
115
115
  // 1) Model-facing tools (`tools` is guaranteed by `inject`).
116
116
  registerTools(ctx, plugin)
117
117
 
118
- // 2) System-prompt guidance.
119
- registerPrompt(ctx)
118
+ // 2) System-prompt guidance. `progressive` mode carries these rules in the
119
+ // always-resident `aiterm_discover` description instead, so registering a
120
+ // section there would duplicate them on every request.
121
+ if (resolved.toolDisclosure !== 'progressive') registerPrompt(ctx)
120
122
 
121
123
  // 3) HTTP RPC + SSE, only when the Web composition provides both services.
122
124
  // `ctx.inject` never fires in a headless composition, which is exactly the
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-aiterm",
3
- "version": "0.5.1",
3
+ "version": "0.5.13",
4
4
  "description": "SSH and Telnet terminals for DeepSeek Harness: one real terminal shared by you and the AI, with per-session AI permissions and token-cheap delta reads.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -48,7 +48,7 @@
48
48
  "scripts": {
49
49
  "build": "node scripts/build-client.mjs",
50
50
  "lint": "node --check lib/index.js && for f in lib/host/*.js lib/host/transports/*.js; do node --check \"$f\" || exit 1; done",
51
- "test": "node scripts/smoke-client.mjs",
51
+ "test": "node --test test/*.test.mjs && node scripts/smoke-client.mjs",
52
52
  "build:vendor": "node scripts/build-vendor.mjs"
53
53
  },
54
54
  "dependencies": {