dsh-aiterm 0.5.0 → 0.5.12
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 +104 -22
- package/README.md +208 -26
- package/client/HistoryPanel.jsx +342 -29
- package/client/api.js +44 -3
- package/client/locale.js +40 -2
- package/cordis.patch.yml +1 -0
- package/lib/client.js +30 -30
- package/lib/host/autolog.js +107 -4
- package/lib/host/config.js +14 -0
- package/lib/host/disclosure.js +357 -0
- package/lib/host/exporter.js +447 -159
- package/lib/host/history-store.js +1735 -295
- package/lib/host/permission.js +13 -0
- package/lib/host/prompt.js +24 -4
- package/lib/host/registry.js +858 -76
- package/lib/host/routes.js +45 -2
- package/lib/host/tools.js +280 -22
- package/lib/host/transports/ssh.js +1 -1
- package/lib/index.js +2 -2
- package/package.json +8 -6
- package/scripts/build-vendor.mjs +37 -0
- package/scripts/smoke-client.mjs +193 -6
- package/vendor/README.md +31 -0
- package/vendor/ssh2.LICENSE +19 -0
- package/vendor/ssh2.cjs +20124 -0
package/lib/host/registry.js
CHANGED
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
* and out to SSE subscribers.
|
|
11
11
|
*/
|
|
12
12
|
|
|
13
|
+
import { createHash } from 'node:crypto'
|
|
13
14
|
import { join } from 'node:path'
|
|
14
15
|
|
|
15
16
|
import { connect as connectSsh } from './transports/ssh.js'
|
|
@@ -389,17 +390,41 @@ export class SessionRegistry {
|
|
|
389
390
|
* @returns {Promise<{ transport: 'ssh' | 'telnet', host: string, port: number, username: string, auth: object, title: string, profileId: string }>} target.
|
|
390
391
|
*/
|
|
391
392
|
async resolveProfileTarget(profileId, input, actor) {
|
|
393
|
+
// A saved profile may hold a password/private key. The AI must not be able
|
|
394
|
+
// to redirect those credentials by supplying an address/auth override, so
|
|
395
|
+
// reject any such key *before* reading secrets. Human callers keep the
|
|
396
|
+
// documented form-override behaviour.
|
|
397
|
+
if (actor === 'ai') {
|
|
398
|
+
// Strict presence check: null/''/false/0/NaN/object are all overrides too.
|
|
399
|
+
// The schema layer must never be the only thing keeping this safe.
|
|
400
|
+
const overridden = ['transport', 'host', 'port', 'username', 'authType'].filter((key) => (
|
|
401
|
+
Object.prototype.hasOwnProperty.call(input, key) && input[key] !== undefined
|
|
402
|
+
))
|
|
403
|
+
if (overridden.length > 0) {
|
|
404
|
+
throw coded(
|
|
405
|
+
'AI_PROFILE_TARGET_DENIED',
|
|
406
|
+
`the AI may not override a saved profile target (${overridden.join(', ')}); pass profileId only`,
|
|
407
|
+
403,
|
|
408
|
+
)
|
|
409
|
+
}
|
|
410
|
+
}
|
|
392
411
|
const saved = await this.loadProfileTarget(profileId)
|
|
393
412
|
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
const
|
|
413
|
+
// For AI the saved profile is authoritative even if a guard ever regresses:
|
|
414
|
+
// no input field participates in transport/host/port/username/auth choice.
|
|
415
|
+
const transport = actor === 'ai'
|
|
416
|
+
? (saved.transport === 'telnet' ? 'telnet' : 'ssh')
|
|
417
|
+
: (input.transport === 'telnet' || input.transport === 'ssh' ? input.transport : saved.transport)
|
|
418
|
+
const rawHost = actor === 'ai' || typeof input.host !== 'string' ? '' : input.host.trim()
|
|
419
|
+
const host = actor === 'ai' ? saved.host : (rawHost.length > 0 ? rawHost : saved.host)
|
|
397
420
|
if (host.length === 0 || host.length > 253 || /[\s/\u0000-\u001f]/.test(host)) {
|
|
398
421
|
throw coded('BAD_TARGET', 'a valid host is required', 400)
|
|
399
422
|
}
|
|
400
|
-
const port =
|
|
401
|
-
|
|
402
|
-
|
|
423
|
+
const port = actor === 'ai'
|
|
424
|
+
? boundInteger(saved.port, transport === 'ssh' ? 22 : 23, 1, 65_535)
|
|
425
|
+
: boundInteger(input.port === undefined ? saved.port : input.port, transport === 'ssh' ? 22 : 23, 1, 65_535)
|
|
426
|
+
const rawUsername = actor === 'ai' || typeof input.username !== 'string' ? '' : input.username.trim()
|
|
427
|
+
const username = actor === 'ai' ? saved.username : (rawUsername.length > 0 ? rawUsername : saved.username)
|
|
403
428
|
if (transport === 'ssh' && username.length === 0) throw coded('BAD_TARGET', 'a username is required for SSH', 400)
|
|
404
429
|
|
|
405
430
|
// The AI never supplies secrets; it may only use what the profile has saved.
|
|
@@ -413,7 +438,7 @@ export class SessionRegistry {
|
|
|
413
438
|
/** @type {{type: string, password?: string, privateKey?: string, passphrase?: string}} */
|
|
414
439
|
let auth = { type: 'none' }
|
|
415
440
|
if (transport === 'ssh') {
|
|
416
|
-
const requested = input.authType
|
|
441
|
+
const requested = actor === 'ai' ? saved.authType : input.authType
|
|
417
442
|
const authType =
|
|
418
443
|
requested === 'agent' || requested === 'privateKey' || requested === 'none' || requested === 'password'
|
|
419
444
|
? requested
|
|
@@ -490,6 +515,81 @@ export class SessionRegistry {
|
|
|
490
515
|
}
|
|
491
516
|
}
|
|
492
517
|
|
|
518
|
+
/**
|
|
519
|
+
* Allocate the next session id.
|
|
520
|
+
*
|
|
521
|
+
* The durable `st-N` reservation (history directory) is what keeps ids unique
|
|
522
|
+
* across plugin reloads and concurrent Host processes. If it is unavailable
|
|
523
|
+
* (history disabled or disk failure) the in-process counter is used, but the
|
|
524
|
+
* caller must skip durable history for that session so it can never append to
|
|
525
|
+
* an old journal that happens to share the reused id.
|
|
526
|
+
* @returns {Promise<{ id: string, durable: boolean }>} allocation.
|
|
527
|
+
*/
|
|
528
|
+
async allocateSessionId() {
|
|
529
|
+
let logIds
|
|
530
|
+
let autologSafe = true
|
|
531
|
+
const loadLogIds = async () => {
|
|
532
|
+
if (typeof this.autolog.listLogIds !== 'function') return undefined
|
|
533
|
+
try {
|
|
534
|
+
return await this.autolog.listLogIds()
|
|
535
|
+
} catch (error) {
|
|
536
|
+
autologSafe = false
|
|
537
|
+
this.log('warn', `[aiterm] cannot scan automatic log ids: ${error?.code ?? (error instanceof Error ? error.message : String(error))}`)
|
|
538
|
+
return null
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
if (this.historyStore !== undefined && typeof this.historyStore.allocateSessionId === 'function') {
|
|
542
|
+
try {
|
|
543
|
+
// The old autolog switch could have written <id>.log for a previous
|
|
544
|
+
// owner with an id that has no surviving history file. Scan once and
|
|
545
|
+
// reject those ids; `init` is idempotent and only awaited here.
|
|
546
|
+
await this.autolog.init().catch(() => {})
|
|
547
|
+
logIds = await loadLogIds()
|
|
548
|
+
if (logIds === null) logIds = undefined
|
|
549
|
+
const id = await this.historyStore.allocateSessionId({
|
|
550
|
+
isIdAvailable: async (candidate) => (
|
|
551
|
+
logIds !== undefined ? !logIds.has(candidate)
|
|
552
|
+
: (typeof this.autolog.hasLog === 'function' ? !(await this.autolog.hasLog(candidate)) : true)
|
|
553
|
+
),
|
|
554
|
+
})
|
|
555
|
+
if (typeof id === 'string' && id.length > 0) {
|
|
556
|
+
const match = /^st-(\d+)$/.exec(id)
|
|
557
|
+
if (match !== null) this.nextId = Math.max(this.nextId, Number(match[1]) + 1)
|
|
558
|
+
return { id, durable: true, autologSafe }
|
|
559
|
+
}
|
|
560
|
+
} catch (error) {
|
|
561
|
+
this.log('warn', `[aiterm] durable session id allocation failed: ${error?.code ?? (error instanceof Error ? error.message : String(error))}`)
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
// Fallback: no durable allocator. History is skipped for this session, but
|
|
565
|
+
// an old `<id>.log` must still not receive a new owner's output.
|
|
566
|
+
await this.autolog.init().catch(() => {})
|
|
567
|
+
if (logIds === undefined) {
|
|
568
|
+
logIds = await loadLogIds()
|
|
569
|
+
if (logIds === null) logIds = undefined
|
|
570
|
+
}
|
|
571
|
+
for (let attempt = 0; attempt < 10_000; attempt += 1) {
|
|
572
|
+
const id = `st-${this.nextId++}`
|
|
573
|
+
if (logIds !== undefined) {
|
|
574
|
+
if (logIds.has(id)) continue
|
|
575
|
+
return { id, durable: false, autologSafe }
|
|
576
|
+
}
|
|
577
|
+
if (typeof this.autolog.hasLog === 'function') {
|
|
578
|
+
let exists = false
|
|
579
|
+
try {
|
|
580
|
+
exists = await this.autolog.hasLog(id)
|
|
581
|
+
} catch {
|
|
582
|
+
autologSafe = false
|
|
583
|
+
return { id, durable: false, autologSafe }
|
|
584
|
+
}
|
|
585
|
+
if (exists) continue
|
|
586
|
+
}
|
|
587
|
+
return { id, durable: false, autologSafe }
|
|
588
|
+
}
|
|
589
|
+
this.log('warn', '[aiterm] could not find an unused session id; automatic log files may be mixed')
|
|
590
|
+
return { id: `st-${this.nextId++}`, durable: false, autologSafe: false }
|
|
591
|
+
}
|
|
592
|
+
|
|
493
593
|
/**
|
|
494
594
|
* Open a new session. Resolves with wire info; a connection failure resolves
|
|
495
595
|
* with `state: 'failed'` and `error` set rather than throwing, so the panel can
|
|
@@ -510,7 +610,8 @@ export class SessionRegistry {
|
|
|
510
610
|
const cols = boundInteger(input.cols, 100, 20, 500)
|
|
511
611
|
const rows = boundInteger(input.rows, 30, 5, 300)
|
|
512
612
|
const now = Date.now()
|
|
513
|
-
const
|
|
613
|
+
const allocation = await this.allocateSessionId()
|
|
614
|
+
const id = allocation.id
|
|
514
615
|
/** @type {SessionRecord} */
|
|
515
616
|
const session = {
|
|
516
617
|
id,
|
|
@@ -520,6 +621,15 @@ export class SessionRegistry {
|
|
|
520
621
|
port: target.port,
|
|
521
622
|
username: target.username,
|
|
522
623
|
profileId: target.profileId,
|
|
624
|
+
profileBinding: target.profileId === undefined
|
|
625
|
+
? undefined
|
|
626
|
+
: {
|
|
627
|
+
transport: target.transport,
|
|
628
|
+
host: target.host,
|
|
629
|
+
port: target.port,
|
|
630
|
+
username: target.username,
|
|
631
|
+
authType: target.auth.type,
|
|
632
|
+
},
|
|
523
633
|
owner: sessionOwner,
|
|
524
634
|
state: 'connecting',
|
|
525
635
|
error: undefined,
|
|
@@ -553,6 +663,10 @@ export class SessionRegistry {
|
|
|
553
663
|
closeReason: undefined,
|
|
554
664
|
reconnecting: false,
|
|
555
665
|
readyPromise: Promise.resolve(),
|
|
666
|
+
historyReady: Promise.resolve(undefined),
|
|
667
|
+
historyId: undefined,
|
|
668
|
+
historyJournal: undefined,
|
|
669
|
+
allowAutoLog: allocation.autologSafe !== false,
|
|
556
670
|
lockTimer: undefined,
|
|
557
671
|
audit: [],
|
|
558
672
|
hostKeyFingerprint: undefined,
|
|
@@ -562,11 +676,14 @@ export class SessionRegistry {
|
|
|
562
676
|
this.trimOwners()
|
|
563
677
|
this.emitSessions()
|
|
564
678
|
this.recordAudit(session, { source: actor === 'ai' ? 'ai' : 'human', action: 'lock', detail: 'connect' })
|
|
565
|
-
if (this.historyStore !== undefined) {
|
|
679
|
+
if (this.historyStore !== undefined && allocation.durable) {
|
|
566
680
|
// Durable history is best effort: a disk failure must not block connecting.
|
|
567
|
-
this
|
|
681
|
+
// The resolved handle is kept so close/export address exactly this
|
|
682
|
+
// incarnation, even when other incarnations share the logical id.
|
|
683
|
+
session.historyReady = this.historyStore
|
|
568
684
|
.openSession({
|
|
569
685
|
id,
|
|
686
|
+
owner: sessionOwner,
|
|
570
687
|
title: session.title,
|
|
571
688
|
transport: session.transport,
|
|
572
689
|
host: session.host,
|
|
@@ -574,21 +691,35 @@ export class SessionRegistry {
|
|
|
574
691
|
username: session.username,
|
|
575
692
|
createdAt: now,
|
|
576
693
|
})
|
|
577
|
-
.
|
|
694
|
+
.then((handle) => {
|
|
695
|
+
if (handle !== null && typeof handle === 'object') {
|
|
696
|
+
session.historyId = handle.historyId
|
|
697
|
+
session.historyJournal = handle.journal
|
|
698
|
+
}
|
|
699
|
+
return handle
|
|
700
|
+
})
|
|
701
|
+
.catch((error) => {
|
|
702
|
+
this.log('warn', `[aiterm] history open failed: ${error instanceof Error ? error.message : String(error)}`)
|
|
703
|
+
return undefined
|
|
704
|
+
})
|
|
578
705
|
}
|
|
579
706
|
// Remember the routing metadata so the first output chunk can write a header
|
|
580
|
-
// block whenever automatic logging is (or later becomes) enabled.
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
707
|
+
// block whenever automatic logging is (or later becomes) enabled. A fallback
|
|
708
|
+
// allocation without a trustworthy log-id scan must not risk an old owner's
|
|
709
|
+
// file, so it opts out of automatic logging entirely.
|
|
710
|
+
if (session.allowAutoLog !== false) {
|
|
711
|
+
try {
|
|
712
|
+
this.autolog.open(id, {
|
|
713
|
+
transport: session.transport,
|
|
714
|
+
host: session.host,
|
|
715
|
+
port: session.port,
|
|
716
|
+
username: session.username,
|
|
717
|
+
title: session.title,
|
|
718
|
+
startedAt: now,
|
|
719
|
+
})
|
|
720
|
+
} catch (error) {
|
|
721
|
+
this.log('debug', `[aiterm] autolog open failed: ${error instanceof Error ? error.message : String(error)}`)
|
|
722
|
+
}
|
|
592
723
|
}
|
|
593
724
|
|
|
594
725
|
session.readyPromise = this.openConnection(session)
|
|
@@ -695,7 +826,7 @@ export class SessionRegistry {
|
|
|
695
826
|
}
|
|
696
827
|
if (this.historyStore !== undefined) {
|
|
697
828
|
try {
|
|
698
|
-
this.historyStore.appendChunk(session.id, chunk, session.lastActivityAt)
|
|
829
|
+
this.historyStore.appendChunk(session.id, chunk, session.lastActivityAt, sessionOwner(session))
|
|
699
830
|
} catch (error) {
|
|
700
831
|
this.log('debug', `[aiterm] history append failed on ${session.id}: ${error instanceof Error ? error.message : String(error)}`)
|
|
701
832
|
}
|
|
@@ -703,7 +834,7 @@ export class SessionRegistry {
|
|
|
703
834
|
// Automatic log file (opt-in, disabled by default): fire-and-forget, queued
|
|
704
835
|
// and bounded, so a disk problem can never reach the terminal stream.
|
|
705
836
|
try {
|
|
706
|
-
this.autolog.append(session.id, chunk)
|
|
837
|
+
if (session.allowAutoLog !== false) this.autolog.append(session.id, chunk)
|
|
707
838
|
} catch (error) {
|
|
708
839
|
this.log('debug', `[aiterm] autolog append failed on ${session.id}: ${error instanceof Error ? error.message : String(error)}`)
|
|
709
840
|
}
|
|
@@ -903,7 +1034,12 @@ export class SessionRegistry {
|
|
|
903
1034
|
this.closeAutoLog(session.id)
|
|
904
1035
|
if (this.historyStore !== undefined) {
|
|
905
1036
|
this.historyStore
|
|
906
|
-
.closeSession(session.id, {
|
|
1037
|
+
.closeSession(session.id, {
|
|
1038
|
+
closedAt: session.updatedAt,
|
|
1039
|
+
owner: sessionOwner(session),
|
|
1040
|
+
historyId: session.historyId,
|
|
1041
|
+
permission: { aiAccess: session.permission.aiAccess },
|
|
1042
|
+
})
|
|
907
1043
|
.catch((error) => this.log('warn', `[aiterm] history close failed: ${error instanceof Error ? error.message : String(error)}`))
|
|
908
1044
|
}
|
|
909
1045
|
try {
|
|
@@ -967,7 +1103,13 @@ export class SessionRegistry {
|
|
|
967
1103
|
if (expireIfIdle(session.permission, Date.now(), this.config)) this.emitState(session)
|
|
968
1104
|
const verdict = checkWrite(session.permission, actor, this.config)
|
|
969
1105
|
if (!verdict.allowed) {
|
|
970
|
-
this.recordAudit(session, {
|
|
1106
|
+
this.recordAudit(session, {
|
|
1107
|
+
source: actor,
|
|
1108
|
+
action: 'deny',
|
|
1109
|
+
detail: `write:${verdict.code ?? 'denied'}`,
|
|
1110
|
+
code: verdict.code,
|
|
1111
|
+
byteLength: Buffer.byteLength(text, 'utf8'),
|
|
1112
|
+
})
|
|
971
1113
|
throw coded(verdict.code ?? 'WRITE_DENIED', verdict.message ?? 'write denied', actor === 'ai' ? 403 : 423)
|
|
972
1114
|
}
|
|
973
1115
|
if (session.state !== 'open' || session.connection === undefined) {
|
|
@@ -987,7 +1129,7 @@ export class SessionRegistry {
|
|
|
987
1129
|
this.armLockTimer(session)
|
|
988
1130
|
}
|
|
989
1131
|
}
|
|
990
|
-
this.recordAudit(session, { source: actor, action: 'write', detail:
|
|
1132
|
+
this.recordAudit(session, { source: actor, action: 'write', detail: 'write:input', byteLength: Buffer.byteLength(text, 'utf8') })
|
|
991
1133
|
return { permission: permissionSnapshot(session.permission) }
|
|
992
1134
|
}
|
|
993
1135
|
|
|
@@ -1197,6 +1339,24 @@ export class SessionRegistry {
|
|
|
1197
1339
|
SessionRegistry.parseCursor(options.cursor) ?? (typeof stored === 'number' ? Math.max(stored, window.firstOffset) : lookbackFloor)
|
|
1198
1340
|
const from = Math.max(startOffset, window.firstOffset)
|
|
1199
1341
|
|
|
1342
|
+
const waitSnapshot = actor === 'ai'
|
|
1343
|
+
? {
|
|
1344
|
+
aiAccess: session.permission.aiAccess,
|
|
1345
|
+
readRevision: session.permission.readRevision ?? 0,
|
|
1346
|
+
}
|
|
1347
|
+
: undefined
|
|
1348
|
+
/** Whether this waiter may still expose output under the current state. */
|
|
1349
|
+
const waitAllowed = () => {
|
|
1350
|
+
if (waitSnapshot === undefined) return { allowed: true }
|
|
1351
|
+
if (
|
|
1352
|
+
session.permission.aiAccess !== waitSnapshot.aiAccess ||
|
|
1353
|
+
(session.permission.readRevision ?? 0) !== waitSnapshot.readRevision
|
|
1354
|
+
) {
|
|
1355
|
+
return { allowed: false, code: 'AI_READ_DENIED' }
|
|
1356
|
+
}
|
|
1357
|
+
const current = checkRead(session.permission, 'ai')
|
|
1358
|
+
return current.allowed ? { allowed: true } : { allowed: false, code: current.code ?? 'AI_READ_DENIED' }
|
|
1359
|
+
}
|
|
1200
1360
|
return new Promise((resolve) => {
|
|
1201
1361
|
let settled = false
|
|
1202
1362
|
/** @type {any} */
|
|
@@ -1215,6 +1375,27 @@ export class SessionRegistry {
|
|
|
1215
1375
|
clearTimeout(timeoutTimer)
|
|
1216
1376
|
if (idleTimer !== undefined) clearTimeout(idleTimer)
|
|
1217
1377
|
session.waiters.delete(waiter)
|
|
1378
|
+
const allowed = waitAllowed()
|
|
1379
|
+
if (!allowed.allowed) {
|
|
1380
|
+
// Any AI permission/takeover change invalidates the whole wait: do
|
|
1381
|
+
// not expose a delta, a pattern result, or consume the cursor. A later
|
|
1382
|
+
// restore cannot retroactively authorize output from this window.
|
|
1383
|
+
this.recordAudit(session, {
|
|
1384
|
+
source: actor,
|
|
1385
|
+
action: 'deny',
|
|
1386
|
+
detail: 'wait:permission_changed',
|
|
1387
|
+
code: allowed.code,
|
|
1388
|
+
})
|
|
1389
|
+
resolve({
|
|
1390
|
+
matched: false,
|
|
1391
|
+
reason: 'permission_changed',
|
|
1392
|
+
text: '',
|
|
1393
|
+
cursor: String(from),
|
|
1394
|
+
atPrompt: this.screenPrompt(session),
|
|
1395
|
+
session: this.info(session),
|
|
1396
|
+
})
|
|
1397
|
+
return
|
|
1398
|
+
}
|
|
1218
1399
|
const text = includeOutput ? this.deltaText(session, from) : ''
|
|
1219
1400
|
// Only a satisfied wait consumes the reader's position. On a timeout the
|
|
1220
1401
|
// output stays available to a delta read instead of silently vanishing.
|
|
@@ -1246,6 +1427,10 @@ export class SessionRegistry {
|
|
|
1246
1427
|
const waiter = {
|
|
1247
1428
|
feed: () => {
|
|
1248
1429
|
if (settled) return
|
|
1430
|
+
if (!waitAllowed().allowed) {
|
|
1431
|
+
finish(false, 'permission_changed')
|
|
1432
|
+
return
|
|
1433
|
+
}
|
|
1249
1434
|
if (until === 'pattern' && pattern !== undefined) {
|
|
1250
1435
|
let text = ''
|
|
1251
1436
|
try {
|
|
@@ -1264,8 +1449,12 @@ export class SessionRegistry {
|
|
|
1264
1449
|
|
|
1265
1450
|
if (until === 'idle') armIdle()
|
|
1266
1451
|
if (until === 'pattern' && pattern !== undefined) {
|
|
1267
|
-
|
|
1268
|
-
|
|
1452
|
+
if (waitAllowed().allowed) {
|
|
1453
|
+
const existing = this.deltaText(session, from)
|
|
1454
|
+
if (pattern.test(existing)) finish(true, 'pattern')
|
|
1455
|
+
} else {
|
|
1456
|
+
finish(false, 'permission_changed')
|
|
1457
|
+
}
|
|
1269
1458
|
}
|
|
1270
1459
|
if (until === 'exit' && session.state !== 'open') finish(true, 'exit')
|
|
1271
1460
|
})
|
|
@@ -1274,11 +1463,12 @@ export class SessionRegistry {
|
|
|
1274
1463
|
/**
|
|
1275
1464
|
* Query output history for one session (live sessions use the memory log,
|
|
1276
1465
|
* closed sessions are read from the durable journal), or list sessions.
|
|
1277
|
-
* @param {{ actor?: 'human' | 'ai', sessionId?: string, owner?: unknown, since?: unknown, until?: unknown, search?: string, context?: unknown, maxMatches?: unknown, maxBytes?: unknown, limit?: unknown }} [query] query.
|
|
1466
|
+
* @param {{ actor?: 'human' | 'ai', sessionId?: string, historyId?: string, owner?: unknown, since?: unknown, until?: unknown, search?: string, context?: unknown, maxMatches?: unknown, maxBytes?: unknown, limit?: unknown, offset?: unknown, snapshot?: string }} [query] query.
|
|
1278
1467
|
* @returns {Promise<Record<string, unknown>>} query result.
|
|
1279
1468
|
*/
|
|
1280
1469
|
async historyQuery(query = {}) {
|
|
1281
|
-
|
|
1470
|
+
let sessionId = typeof query.sessionId === 'string' && query.sessionId.length > 0 ? query.sessionId : undefined
|
|
1471
|
+
const historyId = typeof query.historyId === 'string' && query.historyId.length > 0 ? query.historyId : undefined
|
|
1282
1472
|
const actor = query.actor === 'human' ? 'human' : 'ai'
|
|
1283
1473
|
const wanted = normalizeOwner(query.owner)
|
|
1284
1474
|
const since = parseTimestamp(query.since)
|
|
@@ -1286,14 +1476,40 @@ export class SessionRegistry {
|
|
|
1286
1476
|
const maxBytes = boundInteger(query.maxBytes, this.config.aiReadMaxBytes, 256, 16 * 1024 * 1024)
|
|
1287
1477
|
const maxMatches = boundInteger(query.maxMatches, 20, 1, 500)
|
|
1288
1478
|
const limit = boundInteger(query.limit, 20, 1, 200)
|
|
1479
|
+
const offset = boundInteger(query.offset, 0, 0, 100_000)
|
|
1480
|
+
const requestedSnapshot = typeof query.snapshot === 'string' && query.snapshot.length > 0 ? query.snapshot : undefined
|
|
1481
|
+
if (historyId !== undefined && sessionId === undefined) {
|
|
1482
|
+
if (this.historyStore === undefined) throw coded('SESSION_NOT_FOUND', 'no durable history is available', 404)
|
|
1483
|
+
const exact = await this.historyStore.resolveByHistoryId(historyId, wanted, actor)
|
|
1484
|
+
if (exact === undefined) throw coded('SESSION_NOT_FOUND', 'the requested history incarnation does not exist', 404)
|
|
1485
|
+
sessionId = exact.recording.id
|
|
1486
|
+
// Permission is enforced below: an active live incarnation uses its
|
|
1487
|
+
// in-memory permission; a closed one uses the recorded close permission.
|
|
1488
|
+
}
|
|
1289
1489
|
if (sessionId === undefined) {
|
|
1290
|
-
|
|
1490
|
+
const page = await this.historySessionsPage({
|
|
1491
|
+
limit, offset, snapshot: requestedSnapshot, since, until, owner: wanted, actor,
|
|
1492
|
+
})
|
|
1493
|
+
return {
|
|
1494
|
+
sessions: page.sessions,
|
|
1495
|
+
truncated: page.truncated,
|
|
1496
|
+
total: page.total,
|
|
1497
|
+
snapshot: page.snapshot,
|
|
1498
|
+
...(page.stale === true ? { stale: true } : {}),
|
|
1499
|
+
...(page.limitReached === true ? { limitReached: true } : {}),
|
|
1500
|
+
scannedBytes: 0,
|
|
1501
|
+
}
|
|
1291
1502
|
}
|
|
1292
1503
|
const session = this.sessions.get(sessionId)
|
|
1293
|
-
|
|
1504
|
+
const liveMatches = session !== undefined &&
|
|
1505
|
+
sessionOwner(session) === wanted &&
|
|
1506
|
+
(historyId === undefined || session.historyId === historyId)
|
|
1507
|
+
if (liveMatches) {
|
|
1294
1508
|
// A session owned by another DSH session is indistinguishable from a
|
|
1295
|
-
// missing one: history must not leak across AI sessions either.
|
|
1296
|
-
|
|
1509
|
+
// missing one: history must not leak across AI sessions either. An AI
|
|
1510
|
+
// caller without a resolved owner fails closed rather than falling into
|
|
1511
|
+
// the legacy bucket.
|
|
1512
|
+
if (actor === 'ai' && wanted === null) throw coded('SESSION_NOT_FOUND', `session ${sessionId} does not exist`, 404)
|
|
1297
1513
|
// Reading history is still reading: the session's AI permission applies.
|
|
1298
1514
|
const verdict = checkRead(session.permission, actor)
|
|
1299
1515
|
if (!verdict.allowed) {
|
|
@@ -1322,6 +1538,12 @@ export class SessionRegistry {
|
|
|
1322
1538
|
}
|
|
1323
1539
|
const slice = session.output.slice(from, maxBytes)
|
|
1324
1540
|
const text = slice.text
|
|
1541
|
+
this.recordAudit(session, {
|
|
1542
|
+
source: actor,
|
|
1543
|
+
action: 'read',
|
|
1544
|
+
detail: 'history:slice',
|
|
1545
|
+
byteLength: Buffer.byteLength(text, 'utf8'),
|
|
1546
|
+
})
|
|
1325
1547
|
return {
|
|
1326
1548
|
text,
|
|
1327
1549
|
truncated: slice.truncated === true,
|
|
@@ -1331,53 +1553,136 @@ export class SessionRegistry {
|
|
|
1331
1553
|
complete: true,
|
|
1332
1554
|
}
|
|
1333
1555
|
}
|
|
1334
|
-
// A session that is no longer live
|
|
1335
|
-
//
|
|
1336
|
-
if (
|
|
1556
|
+
// A session that is no longer live. Provenance comes from the journal
|
|
1557
|
+
// header, never from the process-local (and reload-lossy) owner map.
|
|
1558
|
+
if (actor === 'ai' && wanted === null) throw coded('SESSION_NOT_FOUND', `session ${sessionId} does not exist`, 404)
|
|
1337
1559
|
if (this.historyStore === undefined) {
|
|
1338
1560
|
throw coded('SESSION_NOT_FOUND', `session ${sessionId} is not live and durable history is unavailable`, 404)
|
|
1339
1561
|
}
|
|
1340
|
-
const
|
|
1341
|
-
|
|
1562
|
+
const resolved = await this.historyStore.resolveForRead(sessionId, wanted, actor, historyId)
|
|
1563
|
+
if (resolved === undefined) throw coded('SESSION_NOT_FOUND', `session ${sessionId} does not exist`, 404)
|
|
1564
|
+
/** @type {Record<string, unknown>} */
|
|
1565
|
+
const options = {
|
|
1342
1566
|
since,
|
|
1343
1567
|
until,
|
|
1344
1568
|
search: typeof query.search === 'string' && query.search.length > 0 ? query.search : undefined,
|
|
1345
1569
|
context: boundInteger(query.context, 0, 0, 5),
|
|
1346
1570
|
maxMatches,
|
|
1347
1571
|
maxBytes,
|
|
1348
|
-
})
|
|
1349
|
-
if (result.entry === undefined && result.matches.length === 0 && result.scannedBytes === 0) {
|
|
1350
|
-
throw coded('SESSION_NOT_FOUND', `no history is stored for session ${sessionId}`, 404)
|
|
1351
1572
|
}
|
|
1352
|
-
|
|
1573
|
+
if (resolved.kind === 'attributed') {
|
|
1574
|
+
if (actor === 'ai' && !this.historyStore.canAiRead(resolved.recording)) {
|
|
1575
|
+
throw coded(
|
|
1576
|
+
'AI_READ_DENIED',
|
|
1577
|
+
'AI permission for this closed session was write-only (只写) or was never recorded; reading its history is not allowed',
|
|
1578
|
+
403,
|
|
1579
|
+
)
|
|
1580
|
+
}
|
|
1581
|
+
return this.historyStore.queryRecording(resolved.recording, options)
|
|
1582
|
+
}
|
|
1583
|
+
// Legacy journals are only reachable through the explicit human, no-owner
|
|
1584
|
+
// bucket; `resolveForRead` already enforced that.
|
|
1585
|
+
return this.historyStore.queryLegacy(resolved.entry, options)
|
|
1353
1586
|
}
|
|
1354
1587
|
|
|
1355
1588
|
/**
|
|
1356
|
-
* @param {{ limit?: unknown, since?: unknown, until?: unknown, owner?: unknown }} [options] list options.
|
|
1589
|
+
* @param {{ limit?: unknown, since?: unknown, until?: unknown, owner?: unknown, actor?: 'human' | 'ai' }} [options] list options.
|
|
1357
1590
|
* @returns {Promise<Array<Record<string, unknown>>>} live sessions first, then past ones.
|
|
1358
1591
|
*/
|
|
1359
1592
|
async historySessions(options = {}) {
|
|
1593
|
+
const page = await this.historySessionsPage(options)
|
|
1594
|
+
return page.sessions
|
|
1595
|
+
}
|
|
1596
|
+
|
|
1597
|
+
/**
|
|
1598
|
+
* Paginated catalog listing. Only the **active incarnation** of a current
|
|
1599
|
+
* live session is removed from the durable past; older incarnations sharing
|
|
1600
|
+
* the same logical id remain listed.
|
|
1601
|
+
* @param {{ limit?: unknown, offset?: unknown, since?: unknown, until?: unknown, owner?: unknown, actor?: 'human' | 'ai', snapshot?: unknown }} [options] list options.
|
|
1602
|
+
* @returns {Promise<{ sessions: Array<Record<string, unknown>>, truncated: boolean, total: number, snapshot: string, stale?: boolean }>} page.
|
|
1603
|
+
*/
|
|
1604
|
+
async historySessionsPage(options = {}) {
|
|
1360
1605
|
const limit = boundInteger(options.limit, 20, 1, 200)
|
|
1606
|
+
const offset = boundInteger(options.offset, 0, 0, 100_000)
|
|
1607
|
+
const requestedSnapshot = typeof options.snapshot === 'string' && options.snapshot.length > 0 ? options.snapshot : undefined
|
|
1361
1608
|
const wanted = normalizeOwner(options.owner)
|
|
1609
|
+
const actor = options.actor === 'human' ? 'human' : 'ai'
|
|
1362
1610
|
const since = parseTimestamp(options.since)
|
|
1363
1611
|
const until = parseTimestamp(options.until)
|
|
1364
1612
|
/** @type {Array<Record<string, unknown>>} */
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1613
|
+
let live = []
|
|
1614
|
+
if (!(actor === 'ai' && wanted === null)) {
|
|
1615
|
+
live = [...this.sessions.values()]
|
|
1616
|
+
.filter((session) => sessionOwner(session) === wanted)
|
|
1617
|
+
.map((session) => this.catalogEntry(session))
|
|
1618
|
+
}
|
|
1619
|
+
/** @type {Array<Record<string, unknown>>} */
|
|
1620
|
+
const past = []
|
|
1621
|
+
let pastTotal = 0
|
|
1622
|
+
let pastTruncated = false
|
|
1369
1623
|
if (this.historyStore !== undefined) {
|
|
1370
1624
|
try {
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1625
|
+
const page = await this.historyStore.listRecordingsPage({
|
|
1626
|
+
limit: 20_000,
|
|
1627
|
+
offset: 0,
|
|
1628
|
+
since,
|
|
1629
|
+
until,
|
|
1630
|
+
owner: wanted,
|
|
1631
|
+
})
|
|
1632
|
+
pastTotal = page.total
|
|
1633
|
+
pastTruncated = page.truncated
|
|
1634
|
+
for (const recording of page.recordings) {
|
|
1635
|
+
if (actor === 'ai' && wanted === null) continue
|
|
1636
|
+
past.push(historyEntry(recording))
|
|
1637
|
+
}
|
|
1638
|
+
if (actor === 'human' && wanted === null) {
|
|
1639
|
+
const attributedIds = new Set(past.map((entry) => entry.id))
|
|
1640
|
+
const legacyPage = await this.historyStore.listLegacySessionsPage({ limit: 20_000, offset: 0, since, until })
|
|
1641
|
+
let legacyAdded = 0
|
|
1642
|
+
let legacyDuplicates = 0
|
|
1643
|
+
pastTruncated = pastTruncated || legacyPage.truncated
|
|
1644
|
+
for (const entry of legacyPage.sessions) {
|
|
1645
|
+
if (attributedIds.has(entry.id)) {
|
|
1646
|
+
legacyDuplicates += 1
|
|
1647
|
+
continue
|
|
1648
|
+
}
|
|
1649
|
+
past.push(entry)
|
|
1650
|
+
legacyAdded += 1
|
|
1651
|
+
}
|
|
1652
|
+
// Count the full legacy total (not just the fetched page) minus the
|
|
1653
|
+
// duplicate rows actually observed. This avoids undercounting when the
|
|
1654
|
+
// 20k legacy page itself is truncated while still ignoring overlaps.
|
|
1655
|
+
pastTotal += Math.max(legacyAdded, legacyPage.total - legacyDuplicates)
|
|
1656
|
+
}
|
|
1374
1657
|
} catch {
|
|
1375
|
-
|
|
1658
|
+
// Best effort: an unreadable store never breaks the live list.
|
|
1376
1659
|
}
|
|
1377
1660
|
}
|
|
1378
|
-
const
|
|
1379
|
-
const
|
|
1380
|
-
|
|
1661
|
+
const liveHistoryIds = new Set(live.map((entry) => entry.historyId).filter((value) => typeof value === 'string'))
|
|
1662
|
+
const filteredPast = past.filter((entry) => !(
|
|
1663
|
+
typeof entry.historyId === 'string' && liveHistoryIds.has(entry.historyId)
|
|
1664
|
+
))
|
|
1665
|
+
const combined = [...live, ...filteredPast]
|
|
1666
|
+
// `total` is the truthful combined count; the underlying store page cap is
|
|
1667
|
+
// 20k and its truncated flag is surfaced when even that was exceeded.
|
|
1668
|
+
const total = Math.max(combined.length, live.length + pastTotal - (past.length - filteredPast.length))
|
|
1669
|
+
// The fetched set is bounded (recordings page and/or legacy page). The
|
|
1670
|
+
// source limit matters only once this request has actually reached the end
|
|
1671
|
+
// of the fetched set; earlier pages must remain pageable.
|
|
1672
|
+
const available = combined.length
|
|
1673
|
+
const snapshot = catalogSnapshot(combined)
|
|
1674
|
+
if (requestedSnapshot !== undefined && requestedSnapshot !== snapshot) {
|
|
1675
|
+
return { sessions: [], total, truncated: true, stale: true, snapshot, limitReached: false }
|
|
1676
|
+
}
|
|
1677
|
+
const visible = combined.slice(offset, offset + limit)
|
|
1678
|
+
const limitReached = total > available && offset + visible.length >= available
|
|
1679
|
+
return {
|
|
1680
|
+
sessions: visible,
|
|
1681
|
+
total,
|
|
1682
|
+
truncated: pastTruncated || offset + visible.length < total,
|
|
1683
|
+
snapshot,
|
|
1684
|
+
limitReached,
|
|
1685
|
+
}
|
|
1381
1686
|
}
|
|
1382
1687
|
|
|
1383
1688
|
/**
|
|
@@ -1397,6 +1702,7 @@ export class SessionRegistry {
|
|
|
1397
1702
|
bytes: session.bytesIn,
|
|
1398
1703
|
lastTs: session.lastOutputAt,
|
|
1399
1704
|
live: session.state === 'open' || session.state === 'connecting',
|
|
1705
|
+
historyId: session.historyId,
|
|
1400
1706
|
}
|
|
1401
1707
|
}
|
|
1402
1708
|
|
|
@@ -1679,12 +1985,49 @@ export class SessionRegistry {
|
|
|
1679
1985
|
// the in-memory auth captured when the session was first created.
|
|
1680
1986
|
let auth = session.auth
|
|
1681
1987
|
if (typeof session.profileId === 'string' && session.profileId.length > 0) {
|
|
1988
|
+
const binding = session.profileBinding
|
|
1989
|
+
const transport = session.targetTransport === 'telnet' ? 'telnet' : 'ssh'
|
|
1990
|
+
let profile
|
|
1682
1991
|
try {
|
|
1683
|
-
|
|
1684
|
-
|
|
1992
|
+
// Telnet never uses profile secrets; reading them can fail for a
|
|
1993
|
+
// profile whose saved authType is password but has no secret.
|
|
1994
|
+
profile = transport === 'telnet'
|
|
1995
|
+
? await this.profiles.get(session.profileId)
|
|
1996
|
+
: await this.profiles.connectionFor(session.profileId)
|
|
1685
1997
|
} catch (error) {
|
|
1998
|
+
if (actor === 'ai') {
|
|
1999
|
+
throw coded(
|
|
2000
|
+
'PROFILE_UNAVAILABLE',
|
|
2001
|
+
'the saved profile could not be read for this reconnect; reconnect it from the panel or reopen it',
|
|
2002
|
+
409,
|
|
2003
|
+
)
|
|
2004
|
+
}
|
|
1686
2005
|
this.log('warn', `[aiterm] profile ${session.profileId} unavailable for reconnect: ${error instanceof Error ? error.message : String(error)}`)
|
|
1687
2006
|
}
|
|
2007
|
+
if (profile !== undefined) {
|
|
2008
|
+
// Effective auth identity depends on the transport: telnet is always
|
|
2009
|
+
// unauthenticated; only SSH has a profile auth type.
|
|
2010
|
+
const identityMatches = binding !== undefined &&
|
|
2011
|
+
profile.transport === binding.transport &&
|
|
2012
|
+
profile.host === binding.host &&
|
|
2013
|
+
profile.port === binding.port &&
|
|
2014
|
+
profile.username === binding.username &&
|
|
2015
|
+
(transport === 'telnet' || profile.auth?.type === binding.authType)
|
|
2016
|
+
if (!identityMatches) {
|
|
2017
|
+
if (actor === 'ai') {
|
|
2018
|
+
throw coded(
|
|
2019
|
+
'PROFILE_TARGET_CHANGED',
|
|
2020
|
+
'the saved profile target or auth identity changed after this session opened; reopen it from the panel instead of reconnecting',
|
|
2021
|
+
409,
|
|
2022
|
+
)
|
|
2023
|
+
}
|
|
2024
|
+
// Human reconnect must not send a NEW profile secret to the old
|
|
2025
|
+
// endpoint. Reuse the original session auth (or fail if unavailable).
|
|
2026
|
+
auth = session.auth
|
|
2027
|
+
} else if (transport === 'ssh' && profile.auth !== undefined) {
|
|
2028
|
+
auth = profile.auth
|
|
2029
|
+
}
|
|
2030
|
+
}
|
|
1688
2031
|
}
|
|
1689
2032
|
if (auth === undefined || auth === null) {
|
|
1690
2033
|
throw coded(
|
|
@@ -1783,37 +2126,395 @@ export class SessionRegistry {
|
|
|
1783
2126
|
* Export stored output history as human-readable text log files.
|
|
1784
2127
|
*
|
|
1785
2128
|
* Writes into `<dataDir>/exports/` and returns the written paths so the user
|
|
1786
|
-
* can pick them up from the Host file panel.
|
|
1787
|
-
*
|
|
2129
|
+
* can pick them up from the Host file panel. Selection and readability are
|
|
2130
|
+
* owner-scoped: `all` means every session owned by the caller, never every
|
|
2131
|
+
* journal on disk. AI export additionally obeys the live or recorded AI
|
|
2132
|
+
* permission; an unknown closed permission fails closed.
|
|
2133
|
+
* @param {{ sessionId?: unknown, historyId?: unknown, all?: unknown, since?: unknown, until?: unknown, owner?: unknown, actor?: 'human' | 'ai' }} [options] selection.
|
|
1788
2134
|
* @returns {Promise<{ dir: string, files: Array<{ sessionId: string, path: string, bytes: number, lines: number }> }>} export result.
|
|
1789
|
-
* @throws {import('./util.js').CodedError} `HISTORY_UNAVAILABLE`, `SESSION_NOT_FOUND` or `BAD_TARGET`.
|
|
2135
|
+
* @throws {import('./util.js').CodedError} `HISTORY_UNAVAILABLE`, `SESSION_NOT_FOUND`, `AI_READ_DENIED` or `BAD_TARGET`.
|
|
1790
2136
|
*/
|
|
1791
2137
|
async exportHistory(options = {}) {
|
|
1792
2138
|
if (this.historyStore === undefined) {
|
|
1793
2139
|
throw coded('HISTORY_UNAVAILABLE', 'durable history is not available; the plugin cannot export logs', 503)
|
|
1794
2140
|
}
|
|
1795
2141
|
const opts = options !== null && typeof options === 'object' ? options : {}
|
|
2142
|
+
const actor = opts.actor === 'human' ? 'human' : 'ai'
|
|
1796
2143
|
const wanted = normalizeOwner(opts.owner)
|
|
1797
2144
|
const sessionId = typeof opts.sessionId === 'string' && opts.sessionId.length > 0 ? opts.sessionId : undefined
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
|
|
2145
|
+
const historyId = typeof opts.historyId === 'string' && opts.historyId.length > 0 ? opts.historyId : undefined
|
|
2146
|
+
const store = this.historyStore
|
|
2147
|
+
const dir = join(this.dataDir, 'exports')
|
|
2148
|
+
const since = parseTimestamp(opts.since)
|
|
2149
|
+
const until = parseTimestamp(opts.until)
|
|
2150
|
+
// An AI caller without a resolved owner fails closed; it never falls into
|
|
2151
|
+
// the legacy bucket and never gets a host-wide export.
|
|
2152
|
+
if (actor === 'ai' && wanted === null) {
|
|
2153
|
+
throw coded('SESSION_NOT_FOUND', 'no owner-scoped history is available for this caller', 404)
|
|
2154
|
+
}
|
|
2155
|
+
if (historyId !== undefined && opts.all === true) {
|
|
2156
|
+
throw coded('BAD_TARGET', 'historyId cannot be combined with all: true')
|
|
2157
|
+
}
|
|
2158
|
+
|
|
2159
|
+
const candidate = sessionId !== undefined ? this.sessions.get(sessionId) : undefined
|
|
2160
|
+
if (candidate !== undefined && sessionOwner(candidate) === wanted) {
|
|
2161
|
+
// A fire-and-forget open from create() may still be reserving the file.
|
|
2162
|
+
await candidate.historyReady
|
|
2163
|
+
}
|
|
2164
|
+
|
|
2165
|
+
// Every readable live incarnation, plus every readable recorded
|
|
2166
|
+
// incarnation. Do NOT dedupe by logical id: an older incarnation is its own
|
|
2167
|
+
// addressable record and `all` must include it.
|
|
2168
|
+
const ownedLive = [...this.sessions.values()].filter((session) => sessionOwner(session) === wanted)
|
|
2169
|
+
const liveRecords = ownedLive.filter((session) => actor === 'human' || checkRead(session.permission, 'ai').allowed)
|
|
2170
|
+
const deniedLive = actor === 'ai' && opts.all === true
|
|
2171
|
+
? ownedLive.filter((session) => !checkRead(session.permission, 'ai').allowed)
|
|
2172
|
+
: []
|
|
2173
|
+
await Promise.allSettled(liveRecords.map((session) => session.historyReady))
|
|
2174
|
+
const liveById = new Map(liveRecords.map((session) => [session.id, session]))
|
|
2175
|
+
const liveByAddress = new Map()
|
|
2176
|
+
for (const record of liveRecords) {
|
|
2177
|
+
liveByAddress.set(record.historyId ? `history:${record.historyId}` : `live:${record.id}`, record)
|
|
2178
|
+
}
|
|
2179
|
+
const liveEntries = liveRecords.map((session) => ({
|
|
2180
|
+
...this.catalogEntry(session),
|
|
2181
|
+
address: session.historyId ? `history:${session.historyId}` : `live:${session.id}`,
|
|
2182
|
+
}))
|
|
2183
|
+
|
|
2184
|
+
let recordings = []
|
|
2185
|
+
let deniedRecordings = []
|
|
2186
|
+
let ownedRecordings = []
|
|
2187
|
+
let ownedTotal = 0
|
|
2188
|
+
try {
|
|
2189
|
+
// Keep the full owner recording snapshot: a live session may close
|
|
2190
|
+
// during the export, and the durable journal must still be resolvable
|
|
2191
|
+
// when its active writer disappears. The selection is deduped below,
|
|
2192
|
+
// never the lookup.
|
|
2193
|
+
const ownedPage = await store.listRecordingsPage({ limit: 20_000, offset: 0, owner: wanted })
|
|
2194
|
+
ownedRecordings = ownedPage.recordings
|
|
2195
|
+
ownedTotal = ownedPage.total
|
|
2196
|
+
const liveHistoryIds = new Set(ownedLive.map((session) => session.historyId).filter((value) => typeof value === 'string'))
|
|
2197
|
+
const selectable = ownedRecordings.filter((recording) => !(
|
|
2198
|
+
typeof recording.historyId === 'string' && liveHistoryIds.has(recording.historyId)
|
|
2199
|
+
))
|
|
2200
|
+
recordings = actor === 'human' ? selectable : selectable.filter((recording) => store.canAiRead(recording))
|
|
2201
|
+
if (actor === 'ai' && opts.all === true) {
|
|
2202
|
+
deniedRecordings = selectable.filter((recording) => !store.canAiRead(recording))
|
|
2203
|
+
}
|
|
2204
|
+
} catch {
|
|
2205
|
+
recordings = []
|
|
2206
|
+
}
|
|
2207
|
+
const legacyEntries = []
|
|
2208
|
+
const legacyJournalByAddress = new Map()
|
|
2209
|
+
if (actor === 'human' && wanted === null) {
|
|
2210
|
+
try {
|
|
2211
|
+
for (const entry of await store.listLegacySessions({ limit: 10000 })) {
|
|
2212
|
+
legacyEntries.push({ ...entry, address: `legacy:${entry.id}` })
|
|
2213
|
+
legacyJournalByAddress.set(`legacy:${entry.id}`, store.legacyFileFor(entry.id))
|
|
2214
|
+
}
|
|
2215
|
+
} catch {
|
|
2216
|
+
// best effort: an unreadable legacy catalog does not break owner data
|
|
2217
|
+
}
|
|
1801
2218
|
}
|
|
1802
|
-
|
|
2219
|
+
|
|
2220
|
+
const catalog = [
|
|
2221
|
+
...recordings.map((recording) => ({
|
|
2222
|
+
...historyEntry(recording),
|
|
2223
|
+
address: `history:${recording.historyId}`,
|
|
2224
|
+
})),
|
|
2225
|
+
...legacyEntries,
|
|
2226
|
+
]
|
|
1803
2227
|
const historyStore = {
|
|
1804
|
-
|
|
2228
|
+
flush: () => store.flush(),
|
|
2229
|
+
listSessions: async (query) => {
|
|
2230
|
+
const max = boundInteger(query?.limit, 20000, 1, 20000)
|
|
2231
|
+
return catalog.slice(0, max)
|
|
2232
|
+
},
|
|
2233
|
+
fileFor: (address) => {
|
|
2234
|
+
const live = liveByAddress.get(address)
|
|
2235
|
+
if (live !== undefined) {
|
|
2236
|
+
const active = store.activeJournal(live.id, wanted, live.historyId)
|
|
2237
|
+
if (active !== undefined) {
|
|
2238
|
+
// Permission can change while the export is running. Re-check at
|
|
2239
|
+
// the point of use instead of trusting the pre-flight snapshot.
|
|
2240
|
+
if (actor === 'ai' && !checkRead(live.permission, 'ai').allowed) {
|
|
2241
|
+
throw coded('AI_READ_DENIED', 'AI permission for this live incarnation is write-only (只写)', 403)
|
|
2242
|
+
}
|
|
2243
|
+
return active
|
|
2244
|
+
}
|
|
2245
|
+
// The session may have closed while this export was flushing. Its
|
|
2246
|
+
// durable recording is still the exact incarnation; re-check owner
|
|
2247
|
+
// and the newly recorded closed permission before reading it.
|
|
2248
|
+
if (typeof live.historyId === 'string') {
|
|
2249
|
+
const recording = store.recordingByHistoryIdSync(live.historyId)
|
|
2250
|
+
if (recording === undefined || recording.owner !== wanted) return undefined
|
|
2251
|
+
if (actor === 'ai' && !store.canAiRead(recording)) {
|
|
2252
|
+
throw coded('AI_READ_DENIED', 'AI permission for this closed incarnation is write-only (只写) or unknown', 403)
|
|
2253
|
+
}
|
|
2254
|
+
return recording.journal
|
|
2255
|
+
}
|
|
2256
|
+
return undefined
|
|
2257
|
+
}
|
|
2258
|
+
if (address.startsWith('history:')) {
|
|
2259
|
+
const recording = store.recordingByHistoryIdSync(address.slice('history:'.length))
|
|
2260
|
+
if (recording === undefined || recording.owner !== wanted) return undefined
|
|
2261
|
+
if (actor === 'ai' && !store.canAiRead(recording)) {
|
|
2262
|
+
throw coded('AI_READ_DENIED', 'AI permission for this closed incarnation is write-only (只写) or unknown', 403)
|
|
2263
|
+
}
|
|
2264
|
+
return recording.journal
|
|
2265
|
+
}
|
|
2266
|
+
if (legacyJournalByAddress.has(address)) return legacyJournalByAddress.get(address)
|
|
2267
|
+
return undefined
|
|
2268
|
+
},
|
|
2269
|
+
beforeRead: (address) => {
|
|
2270
|
+
const live = liveByAddress.get(address)
|
|
2271
|
+
if (live !== undefined) {
|
|
2272
|
+
const active = store.activeJournal(live.id, wanted, live.historyId)
|
|
2273
|
+
if (active !== undefined) {
|
|
2274
|
+
if (actor === 'ai' && !checkRead(live.permission, 'ai').allowed) {
|
|
2275
|
+
throw coded('AI_READ_DENIED', 'AI permission for this live incarnation is write-only (只写)', 403)
|
|
2276
|
+
}
|
|
2277
|
+
return
|
|
2278
|
+
}
|
|
2279
|
+
if (typeof live.historyId !== 'string') {
|
|
2280
|
+
throw coded('SESSION_NOT_FOUND', 'the live journal is no longer available', 404)
|
|
2281
|
+
}
|
|
2282
|
+
const recording = store.recordingByHistoryIdSync(live.historyId)
|
|
2283
|
+
if (recording === undefined || recording.owner !== wanted) {
|
|
2284
|
+
throw coded('SESSION_NOT_FOUND', 'the history incarnation is no longer available', 404)
|
|
2285
|
+
}
|
|
2286
|
+
if (actor === 'ai' && !store.canAiRead(recording)) {
|
|
2287
|
+
throw coded('AI_READ_DENIED', 'AI permission for this closed incarnation is write-only (只写) or unknown', 403)
|
|
2288
|
+
}
|
|
2289
|
+
return
|
|
2290
|
+
}
|
|
2291
|
+
if (address.startsWith('history:')) {
|
|
2292
|
+
const recording = store.recordingByHistoryIdSync(address.slice('history:'.length))
|
|
2293
|
+
if (recording === undefined || recording.owner !== wanted) {
|
|
2294
|
+
throw coded('SESSION_NOT_FOUND', 'the history incarnation is no longer available', 404)
|
|
2295
|
+
}
|
|
2296
|
+
if (actor === 'ai' && !store.canAiRead(recording)) {
|
|
2297
|
+
throw coded('AI_READ_DENIED', 'AI permission for this closed incarnation is write-only (只写) or unknown', 403)
|
|
2298
|
+
}
|
|
2299
|
+
return
|
|
2300
|
+
}
|
|
2301
|
+
if (!legacyJournalByAddress.has(address)) {
|
|
2302
|
+
throw coded('SESSION_NOT_FOUND', 'the history source is no longer available', 404)
|
|
2303
|
+
}
|
|
2304
|
+
},
|
|
2305
|
+
}
|
|
2306
|
+
|
|
2307
|
+
// Explicit target: validate exactly that incarnation and pass its address
|
|
2308
|
+
// to the exporter. Old sessionId-only callers get the newest incarnation
|
|
2309
|
+
// for their owner (compatibility), while historyId pins the exact one.
|
|
2310
|
+
let journalKey
|
|
2311
|
+
if (historyId !== undefined) {
|
|
2312
|
+
if (sessionId === undefined) throw coded('BAD_TARGET', 'historyId requires its session id')
|
|
2313
|
+
const live = candidate !== undefined && sessionOwner(candidate) === wanted && candidate.historyId === historyId
|
|
2314
|
+
? candidate
|
|
2315
|
+
: undefined
|
|
2316
|
+
if (live !== undefined) {
|
|
2317
|
+
const verdict = checkRead(live.permission, actor)
|
|
2318
|
+
if (!verdict.allowed) throw coded(verdict.code ?? 'READ_DENIED', verdict.message ?? 'read denied', 403)
|
|
2319
|
+
journalKey = `history:${historyId}`
|
|
2320
|
+
} else {
|
|
2321
|
+
const resolved = await store.resolveForRead(sessionId, wanted, actor, historyId)
|
|
2322
|
+
if (resolved === undefined || resolved.kind !== 'attributed') {
|
|
2323
|
+
throw coded('SESSION_NOT_FOUND', `session ${sessionId} does not exist`, 404)
|
|
2324
|
+
}
|
|
2325
|
+
if (actor === 'ai' && !store.canAiRead(resolved.recording)) {
|
|
2326
|
+
throw coded(
|
|
2327
|
+
'AI_READ_DENIED',
|
|
2328
|
+
'AI permission for this closed session was write-only (只写) or was never recorded; exporting its history is not allowed',
|
|
2329
|
+
403,
|
|
2330
|
+
)
|
|
2331
|
+
}
|
|
2332
|
+
journalKey = `history:${historyId}`
|
|
2333
|
+
}
|
|
2334
|
+
} else if (sessionId !== undefined && opts.all !== true) {
|
|
2335
|
+
const live = candidate !== undefined && sessionOwner(candidate) === wanted ? candidate : undefined
|
|
2336
|
+
if (live !== undefined) {
|
|
2337
|
+
const verdict = checkRead(live.permission, actor)
|
|
2338
|
+
if (!verdict.allowed) throw coded(verdict.code ?? 'READ_DENIED', verdict.message ?? 'read denied', 403)
|
|
2339
|
+
journalKey = live.historyId ? `history:${live.historyId}` : `live:${live.id}`
|
|
2340
|
+
} else {
|
|
2341
|
+
const resolved = await store.resolveForRead(sessionId, wanted, actor)
|
|
2342
|
+
if (resolved === undefined) throw coded('SESSION_NOT_FOUND', `session ${sessionId} does not exist`, 404)
|
|
2343
|
+
if (resolved.kind === 'attributed') {
|
|
2344
|
+
if (actor === 'ai' && !store.canAiRead(resolved.recording)) {
|
|
2345
|
+
throw coded(
|
|
2346
|
+
'AI_READ_DENIED',
|
|
2347
|
+
'AI permission for this closed session was write-only (只写) or was never recorded; exporting its history is not allowed',
|
|
2348
|
+
403,
|
|
2349
|
+
)
|
|
2350
|
+
}
|
|
2351
|
+
journalKey = `history:${resolved.recording.historyId}`
|
|
2352
|
+
} else {
|
|
2353
|
+
// human explicit legacy (owner:null bucket)
|
|
2354
|
+
if (!(actor === 'human' && wanted === null)) {
|
|
2355
|
+
throw coded('SESSION_NOT_FOUND', `session ${sessionId} does not exist`, 404)
|
|
2356
|
+
}
|
|
2357
|
+
journalKey = `legacy:${sessionId}`
|
|
2358
|
+
}
|
|
2359
|
+
}
|
|
2360
|
+
}
|
|
2361
|
+
|
|
2362
|
+
const result = await exportSessions({
|
|
2363
|
+
historyStore,
|
|
2364
|
+
sessions: liveEntries,
|
|
2365
|
+
dir,
|
|
2366
|
+
sessionId,
|
|
2367
|
+
journalKey,
|
|
2368
|
+
all: opts.all === true,
|
|
2369
|
+
since,
|
|
2370
|
+
until,
|
|
2371
|
+
})
|
|
2372
|
+
if (actor === 'ai' && opts.all === true) {
|
|
2373
|
+
const reported = new Set()
|
|
2374
|
+
const details = []
|
|
2375
|
+
let permissionTotal = 0
|
|
2376
|
+
const addPermission = (entry) => {
|
|
2377
|
+
permissionTotal += 1
|
|
2378
|
+
if (details.length < 100) details.push(entry)
|
|
2379
|
+
}
|
|
2380
|
+
for (const recording of deniedRecordings) {
|
|
2381
|
+
const key = recording.historyId ?? recording.id
|
|
2382
|
+
if (reported.has(key)) continue
|
|
2383
|
+
reported.add(key)
|
|
2384
|
+
addPermission({
|
|
2385
|
+
sessionId: recording.id,
|
|
2386
|
+
...(typeof recording.historyId === 'string' ? { historyId: recording.historyId } : {}),
|
|
2387
|
+
code: 'AI_READ_DENIED',
|
|
2388
|
+
message: 'AI permission for this incarnation is write-only (只写) or was never recorded',
|
|
2389
|
+
})
|
|
2390
|
+
}
|
|
2391
|
+
for (const session of deniedLive) {
|
|
2392
|
+
const key = session.historyId ?? session.id
|
|
2393
|
+
if (reported.has(key)) continue
|
|
2394
|
+
reported.add(key)
|
|
2395
|
+
addPermission({
|
|
2396
|
+
sessionId: session.id,
|
|
2397
|
+
...(typeof session.historyId === 'string' ? { historyId: session.historyId } : {}),
|
|
2398
|
+
code: 'AI_READ_DENIED',
|
|
2399
|
+
message: 'AI permission for this live incarnation is write-only (只写)',
|
|
2400
|
+
})
|
|
2401
|
+
}
|
|
2402
|
+
const capacity = Math.max(0, 100 - result.skipped.length)
|
|
2403
|
+
result.skipped.push(...details.slice(0, capacity))
|
|
2404
|
+
result.skippedTotal = (result.skippedTotal ?? result.skipped.length) + permissionTotal
|
|
2405
|
+
}
|
|
2406
|
+
const extraOmitted = Math.max(0, ownedTotal - ownedRecordings.length)
|
|
2407
|
+
if (extraOmitted > 0) {
|
|
2408
|
+
result.omitted = {
|
|
2409
|
+
count: (result.omitted?.count ?? 0) + extraOmitted,
|
|
2410
|
+
limit: result.omitted?.limit ?? 5000,
|
|
2411
|
+
reason: 'EXPORT_LIMIT',
|
|
2412
|
+
}
|
|
2413
|
+
}
|
|
2414
|
+
for (const file of result.files) {
|
|
2415
|
+
const live = liveById.get(file.sessionId)
|
|
2416
|
+
if (live === undefined) continue
|
|
2417
|
+
// Only the live incarnation itself is attributable to the in-memory
|
|
2418
|
+
// session; an older incarnation with the same id is not.
|
|
2419
|
+
if (typeof file.historyId === 'string' && file.historyId !== live.historyId) continue
|
|
2420
|
+
this.recordAudit(live, { source: actor, action: 'read', detail: 'export', byteLength: file.bytes })
|
|
2421
|
+
}
|
|
2422
|
+
return result
|
|
2423
|
+
}
|
|
2424
|
+
|
|
2425
|
+
/**
|
|
2426
|
+
* Explicit human-only view of pre-upgrade, ownerless history.
|
|
2427
|
+
*
|
|
2428
|
+
* The normal panel is owner-bound (the GUI always injects the DSH session id),
|
|
2429
|
+
* so a legitimate human entry point is needed for files that predate
|
|
2430
|
+
* provenance. These methods never attribute the files, never write them, and
|
|
2431
|
+
* refuse every non-human actor; no model tool exposes them.
|
|
2432
|
+
* @param {{ limit?: unknown, since?: unknown, until?: unknown, actor?: 'human' | 'ai' }} [options] options.
|
|
2433
|
+
* @returns {Promise<Array<Record<string, unknown>>>} legacy catalog entries.
|
|
2434
|
+
*/
|
|
2435
|
+
async legacyHistorySessions(options = {}) {
|
|
2436
|
+
const page = await this.legacyHistorySessionsPage(options)
|
|
2437
|
+
return page.sessions
|
|
2438
|
+
}
|
|
2439
|
+
|
|
2440
|
+
/**
|
|
2441
|
+
* Paged human-only legacy listing, with total/truncated so the caller can
|
|
2442
|
+
* page through every old file instead of hitting a silent cap.
|
|
2443
|
+
* @param {{ limit?: unknown, offset?: unknown, since?: unknown, until?: unknown, actor?: 'human' | 'ai' }} [options] options.
|
|
2444
|
+
* @returns {Promise<{ sessions: Array<Record<string, unknown>>, total: number, truncated: boolean, snapshot: string, stale?: boolean }>} page.
|
|
2445
|
+
*/
|
|
2446
|
+
async legacyHistorySessionsPage(options = {}) {
|
|
2447
|
+
if (options.actor !== 'human') {
|
|
2448
|
+
throw coded('HUMAN_ONLY', 'pre-upgrade ownerless history is only available to the human', 403)
|
|
2449
|
+
}
|
|
2450
|
+
if (this.historyStore === undefined) return { sessions: [], total: 0, truncated: false, snapshot: '' }
|
|
2451
|
+
const page = await this.historyStore.listLegacySessionsPage({
|
|
2452
|
+
limit: boundInteger(options.limit, 50, 1, 200),
|
|
2453
|
+
offset: boundInteger(options.offset, 0, 0, 100_000),
|
|
2454
|
+
since: parseTimestamp(options.since),
|
|
2455
|
+
until: parseTimestamp(options.until),
|
|
2456
|
+
})
|
|
2457
|
+
const requested = typeof options.snapshot === 'string' && options.snapshot.length > 0 ? options.snapshot : undefined
|
|
2458
|
+
if (requested !== undefined && page.snapshot !== undefined && requested !== page.snapshot) {
|
|
2459
|
+
return { ...page, sessions: [], truncated: true, stale: true }
|
|
2460
|
+
}
|
|
2461
|
+
return page
|
|
2462
|
+
}
|
|
2463
|
+
|
|
2464
|
+
/**
|
|
2465
|
+
* Search one catalogued legacy journal for the human.
|
|
2466
|
+
* @param {{ sessionId?: unknown, actor?: 'human' | 'ai', since?: unknown, until?: unknown, search?: string, context?: unknown, maxMatches?: unknown, maxBytes?: unknown }} [query] query.
|
|
2467
|
+
* @returns {Promise<Record<string, unknown>>} query result.
|
|
2468
|
+
*/
|
|
2469
|
+
async legacyHistoryQuery(query = {}) {
|
|
2470
|
+
if (query.actor !== 'human') {
|
|
2471
|
+
throw coded('HUMAN_ONLY', 'pre-upgrade ownerless history is only available to the human', 403)
|
|
2472
|
+
}
|
|
2473
|
+
if (this.historyStore === undefined) throw coded('SESSION_NOT_FOUND', 'durable history is unavailable', 404)
|
|
2474
|
+
const sessionId = typeof query.sessionId === 'string' && query.sessionId.length > 0 ? query.sessionId : undefined
|
|
2475
|
+
if (sessionId === undefined) throw coded('BAD_TARGET', 'legacy history query requires a session id')
|
|
2476
|
+
const entry = await this.historyStore.legacyEntry(sessionId)
|
|
2477
|
+
if (entry === undefined) throw coded('SESSION_NOT_FOUND', `no legacy history is stored for session ${sessionId}`, 404)
|
|
2478
|
+
return this.historyStore.queryLegacy(entry, {
|
|
2479
|
+
since: parseTimestamp(query.since),
|
|
2480
|
+
until: parseTimestamp(query.until),
|
|
2481
|
+
search: typeof query.search === 'string' && query.search.length > 0 ? query.search : undefined,
|
|
2482
|
+
context: boundInteger(query.context, 0, 0, 5),
|
|
2483
|
+
maxMatches: boundInteger(query.maxMatches, 20, 1, 500),
|
|
2484
|
+
maxBytes: boundInteger(query.maxBytes, this.config.aiReadMaxBytes, 256, 16 * 1024 * 1024),
|
|
2485
|
+
})
|
|
2486
|
+
}
|
|
2487
|
+
|
|
2488
|
+
/**
|
|
2489
|
+
* Export one catalogued legacy journal for the human.
|
|
2490
|
+
* @param {{ sessionId?: unknown, actor?: 'human' | 'ai', since?: unknown, until?: unknown }} [options] selection.
|
|
2491
|
+
* @returns {Promise<{ dir: string, files: Array<Record<string, unknown>> }>} export result.
|
|
2492
|
+
*/
|
|
2493
|
+
async legacyHistoryExport(options = {}) {
|
|
2494
|
+
if (options.actor !== 'human') {
|
|
2495
|
+
throw coded('HUMAN_ONLY', 'pre-upgrade ownerless history is only available to the human', 403)
|
|
2496
|
+
}
|
|
2497
|
+
if (this.historyStore === undefined) {
|
|
2498
|
+
throw coded('HISTORY_UNAVAILABLE', 'durable history is not available; the plugin cannot export logs', 503)
|
|
2499
|
+
}
|
|
2500
|
+
const sessionId = typeof options.sessionId === 'string' && options.sessionId.length > 0 ? options.sessionId : undefined
|
|
2501
|
+
if (sessionId === undefined) throw coded('BAD_TARGET', 'legacy history export requires a session id')
|
|
2502
|
+
const entry = await this.historyStore.legacyEntry(sessionId)
|
|
2503
|
+
if (entry === undefined) throw coded('SESSION_NOT_FOUND', `no legacy history is stored for session ${sessionId}`, 404)
|
|
2504
|
+
const journal = await this.historyStore.legacyJournal(sessionId)
|
|
2505
|
+
const legacyStore = {
|
|
2506
|
+
fileFor: (id) => (id === sessionId ? journal : undefined),
|
|
1805
2507
|
flush: () => this.historyStore.flush(),
|
|
1806
|
-
listSessions: async (
|
|
1807
|
-
(await this.historyStore.listSessions(query)).filter((entry) => this.ownerOf(entry.id) === wanted),
|
|
2508
|
+
listSessions: async () => [entry],
|
|
1808
2509
|
}
|
|
1809
2510
|
return exportSessions({
|
|
1810
|
-
historyStore,
|
|
1811
|
-
sessions:
|
|
2511
|
+
historyStore: legacyStore,
|
|
2512
|
+
sessions: [],
|
|
1812
2513
|
dir: join(this.dataDir, 'exports'),
|
|
1813
2514
|
sessionId,
|
|
1814
|
-
all:
|
|
1815
|
-
since: parseTimestamp(
|
|
1816
|
-
until: parseTimestamp(
|
|
2515
|
+
all: false,
|
|
2516
|
+
since: parseTimestamp(options.since),
|
|
2517
|
+
until: parseTimestamp(options.until),
|
|
1817
2518
|
})
|
|
1818
2519
|
}
|
|
1819
2520
|
|
|
@@ -1825,15 +2526,18 @@ export class SessionRegistry {
|
|
|
1825
2526
|
audit(options = {}) {
|
|
1826
2527
|
const limit = boundInteger(options.limit, 100, 1, AUDIT_GLOBAL)
|
|
1827
2528
|
const wanted = normalizeOwner(options.owner)
|
|
2529
|
+
const actor = options.actor === 'human' ? 'human' : 'ai'
|
|
2530
|
+
const redact = (entry) => (actor === 'ai' ? redactAuditEntry(entry) : entry)
|
|
1828
2531
|
if (typeof options.sessionId === 'string' && options.sessionId.length > 0) {
|
|
1829
2532
|
const session = this.sessions.get(options.sessionId)
|
|
1830
2533
|
if (session === undefined) return []
|
|
1831
2534
|
if (sessionOwner(session) !== wanted) throw coded('SESSION_NOT_FOUND', `session ${options.sessionId} does not exist`, 404)
|
|
1832
|
-
return session.audit.slice(-limit)
|
|
2535
|
+
return session.audit.slice(-limit).map(redact)
|
|
1833
2536
|
}
|
|
1834
2537
|
return this.globalAudit
|
|
1835
2538
|
.filter((entry) => this.ownerOf(entry.sessionId) === wanted)
|
|
1836
2539
|
.slice(-limit)
|
|
2540
|
+
.map(redact)
|
|
1837
2541
|
}
|
|
1838
2542
|
|
|
1839
2543
|
/**
|
|
@@ -1862,6 +2566,23 @@ export class SessionRegistry {
|
|
|
1862
2566
|
}
|
|
1863
2567
|
}
|
|
1864
2568
|
|
|
2569
|
+
/**
|
|
2570
|
+
* Return a safe audit entry to the AI.
|
|
2571
|
+
*
|
|
2572
|
+
* Historical buffers may contain raw human input in `detail` (older builds did
|
|
2573
|
+
* so for write/deny events). The AI must never receive that text, so every
|
|
2574
|
+
* action is reduced to fixed metadata: keep action/source/code/size/time but
|
|
2575
|
+
* drop the free-form detail. The human panel still sees the original buffer.
|
|
2576
|
+
* @param {Record<string, unknown>} entry audit entry.
|
|
2577
|
+
* @returns {Record<string, unknown>} redacted copy.
|
|
2578
|
+
*/
|
|
2579
|
+
function redactAuditEntry(entry) {
|
|
2580
|
+
/** @type {Record<string, unknown>} */
|
|
2581
|
+
const copy = { ...entry }
|
|
2582
|
+
copy.detail = typeof entry.action === 'string' ? `${entry.action}:redacted` : 'redacted'
|
|
2583
|
+
return copy
|
|
2584
|
+
}
|
|
2585
|
+
|
|
1865
2586
|
/**
|
|
1866
2587
|
* Normalize an owner argument.
|
|
1867
2588
|
*
|
|
@@ -1886,6 +2607,55 @@ function sessionOwner(session) {
|
|
|
1886
2607
|
return normalizeOwner(session.owner)
|
|
1887
2608
|
}
|
|
1888
2609
|
|
|
2610
|
+
/**
|
|
2611
|
+
* Snapshot token for a combined live+past catalog page.
|
|
2612
|
+
* @param {Array<Record<string, any>>} entries entries.
|
|
2613
|
+
* @returns {string} short token.
|
|
2614
|
+
*/
|
|
2615
|
+
function catalogSnapshot(entries) {
|
|
2616
|
+
const payload = entries.map((entry) => {
|
|
2617
|
+
const isLive = entry.live === true
|
|
2618
|
+
// Live sessions are listed in insertion order, not output-activity order:
|
|
2619
|
+
// ordinary output must not invalidate a page snapshot. Membership/close
|
|
2620
|
+
// changes do, because they alter the list itself.
|
|
2621
|
+
return [
|
|
2622
|
+
entry.id ?? '',
|
|
2623
|
+
entry.historyId ?? '',
|
|
2624
|
+
entry.createdAt ?? 0,
|
|
2625
|
+
entry.closedAt ?? '',
|
|
2626
|
+
isLive ? 'live' : '',
|
|
2627
|
+
isLive ? '' : (entry.lastTs ?? 0),
|
|
2628
|
+
].join('\u0000')
|
|
2629
|
+
}).join('\n')
|
|
2630
|
+
return createHash('sha256').update(payload).digest('hex').slice(0, 20)
|
|
2631
|
+
}
|
|
2632
|
+
|
|
2633
|
+
/**
|
|
2634
|
+
* Map a private history recording to the public catalog shape.
|
|
2635
|
+
*
|
|
2636
|
+
* `owner`, `aiAccess` and the journal path are provenance and never leave the
|
|
2637
|
+
* Host through a tool result or browser payload.
|
|
2638
|
+
* @param {Record<string, any>} recording private recording.
|
|
2639
|
+
* @returns {Record<string, unknown>} catalog-shaped entry.
|
|
2640
|
+
*/
|
|
2641
|
+
function historyEntry(recording) {
|
|
2642
|
+
/** @type {Record<string, unknown>} */
|
|
2643
|
+
const entry = {
|
|
2644
|
+
id: recording.id,
|
|
2645
|
+
title: recording.title,
|
|
2646
|
+
transport: recording.transport,
|
|
2647
|
+
host: recording.host,
|
|
2648
|
+
port: recording.port,
|
|
2649
|
+
username: recording.username,
|
|
2650
|
+
createdAt: recording.createdAt,
|
|
2651
|
+
bytes: recording.bytes,
|
|
2652
|
+
lastTs: recording.lastTs,
|
|
2653
|
+
}
|
|
2654
|
+
if (typeof recording.historyId === 'string') entry.historyId = recording.historyId
|
|
2655
|
+
if (recording.closedAt !== undefined) entry.closedAt = recording.closedAt
|
|
2656
|
+
return entry
|
|
2657
|
+
}
|
|
2658
|
+
|
|
1889
2659
|
/**
|
|
1890
2660
|
* Build a view of the registry bound to one owner.
|
|
1891
2661
|
*
|
|
@@ -1894,6 +2664,13 @@ function sessionOwner(session) {
|
|
|
1894
2664
|
* guessing its id. Batch/script runners receive this view and therefore inherit
|
|
1895
2665
|
* the same isolation. Unknown methods fall through bound to the raw registry
|
|
1896
2666
|
* (events/subscription are owner-agnostic on purpose).
|
|
2667
|
+
*
|
|
2668
|
+
* Compatibility note: unknown properties still fall through to the raw registry
|
|
2669
|
+
* so existing batch/script internals keep working. Every NEW owner-sensitive
|
|
2670
|
+
* method must therefore be added to `bound` explicitly; there is deliberately no
|
|
2671
|
+
* blanket owner injection for arbitrary methods because many methods are
|
|
2672
|
+
* host-wide or have different owner semantics. The route/facade integration test
|
|
2673
|
+
* covers the paged history surface.
|
|
1897
2674
|
* @param {SessionRegistry} registry the real registry.
|
|
1898
2675
|
* @param {unknown} owner owning DSH (AI) session id; `null` = legacy bucket.
|
|
1899
2676
|
* @returns {SessionRegistry} owner-scoped facade.
|
|
@@ -1923,9 +2700,14 @@ export function ownerScopedRegistry(registry, owner) {
|
|
|
1923
2700
|
takeOver: (id, actor) => registry.takeOver(id, actor, wanted),
|
|
1924
2701
|
release: (id, actor) => registry.release(id, actor, wanted),
|
|
1925
2702
|
relinquish: (id, actor) => registry.relinquish(id, actor, wanted),
|
|
1926
|
-
audit: (options = {}) => registry.audit({ ...options, owner: wanted }),
|
|
2703
|
+
audit: (options = {}) => registry.audit({ ...options, owner: wanted, actor: options.actor ?? 'ai' }),
|
|
1927
2704
|
historyQuery: (query = {}) => registry.historyQuery({ ...query, owner: wanted }),
|
|
1928
2705
|
historySessions: (options = {}) => registry.historySessions({ ...options, owner: wanted }),
|
|
2706
|
+
historySessionsPage: (options = {}) => registry.historySessionsPage({ ...options, owner: wanted }),
|
|
2707
|
+
legacyHistorySessions: (options = {}) => registry.legacyHistorySessions({ ...options }),
|
|
2708
|
+
legacyHistorySessionsPage: (options = {}) => registry.legacyHistorySessionsPage({ ...options }),
|
|
2709
|
+
legacyHistoryQuery: (query = {}) => registry.legacyHistoryQuery({ ...query }),
|
|
2710
|
+
legacyHistoryExport: (options = {}) => registry.legacyHistoryExport({ ...options }),
|
|
1929
2711
|
exportHistory: (options = {}) => registry.exportHistory({ ...options, owner: wanted }),
|
|
1930
2712
|
activeCount: () => registry.activeCount(wanted),
|
|
1931
2713
|
ownerOf: (id) => registry.ownerOf(id),
|