@unieai/rabi-tool-session-query 0.0.0-stage → 0.2.2-rc.5

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.
@@ -0,0 +1,255 @@
1
+ /**
2
+ * Model text rendering and generic tool-call presentation.
3
+ *
4
+ * @module @unieai/rabi-tool-session-query/presentation
5
+ */
6
+
7
+ import {
8
+ extractSessionEventText,
9
+ type SessionEventSearchHit,
10
+ type SessionEventTraceObservation,
11
+ type SessionEventWindow,
12
+ type SessionLineageTrace,
13
+ type SessionRecord,
14
+ type SessionSearchHit,
15
+ } from '@unieai/rabi-session-query'
16
+ import type {
17
+ SessionEvent,
18
+ SessionId,
19
+ } from '@unieai/rabi-session'
20
+ import type { GenericCallView } from '@unieai/rabi-tools'
21
+ import { workspaceAccess } from './workspace-access.ts'
22
+
23
+ type TitleView = Awaited<ReturnType<typeof workspaceAccess.readTitle>>
24
+ type CompleteTitleMap = Awaited<ReturnType<typeof workspaceAccess.readTitles>>
25
+ type AuthorizedDescendants = ReturnType<typeof workspaceAccess.authorizeDescendants>
26
+
27
+ interface SearchCollection<T> {
28
+ readonly items: T[]
29
+ readonly capped: boolean
30
+ }
31
+
32
+ interface SessionSearchCallArgs {
33
+ readonly query: string
34
+ }
35
+
36
+ interface EventSearchCallArgs {
37
+ readonly query: string
38
+ }
39
+
40
+ interface SessionTargetCallArgs {
41
+ readonly session_id?: string
42
+ }
43
+
44
+ interface EventTargetCallArgs extends SessionTargetCallArgs {
45
+ readonly seq: number
46
+ }
47
+
48
+ function formatSessionSearch(
49
+ collected: SearchCollection<SessionSearchHit>,
50
+ titles: CompleteTitleMap,
51
+ authorizedParents: ReadonlySet<SessionId>,
52
+ ): string {
53
+ if (collected.items.length === 0) return formatEmptySessionSearch()
54
+ const lines = [`Session search results (${collected.items.length}):`]
55
+ for (const [index, hit] of collected.items.entries()) {
56
+ const parent = hit.header.parentSession === undefined
57
+ ? 'root'
58
+ : authorizedParents.has(hit.header.parentSession)
59
+ ? hit.header.parentSession
60
+ : '[outside workspace]'
61
+ const availability = [
62
+ hit.live ? 'live' : undefined,
63
+ hit.persisted ? 'persisted' : undefined,
64
+ ].filter((value): value is string => value !== undefined).join(', ') || 'unavailable'
65
+ lines.push(
66
+ '',
67
+ `${index + 1}. Session ${hit.header.id} — ${workspaceAccess.titleText(titles.get(hit.header.id))}`,
68
+ ` Created: ${formatTime(hit.header.createdAt)}`,
69
+ ` Parent: ${parent}`,
70
+ ` Availability: ${availability}`,
71
+ ` Best match: seq ${hit.bestMatch.seq} | ${hit.bestMatch.type} | ${hit.bestMatch.surface} | ${formatTime(hit.bestMatch.time)}`,
72
+ ` Snippet: ${hit.bestMatch.snippet}`,
73
+ )
74
+ }
75
+ if (collected.capped) {
76
+ lines.push('', 'Result cap reached. Narrow the query or add filters to find additional matches.')
77
+ }
78
+ return lines.join('\n')
79
+ }
80
+
81
+ function formatEmptySessionSearch(): string {
82
+ return 'No prior session matches found.'
83
+ }
84
+
85
+ function formatEventSearch(
86
+ sessionId: SessionId,
87
+ title: TitleView,
88
+ collected: SearchCollection<SessionEventSearchHit>,
89
+ ): string {
90
+ const lines = [`Session ${sessionId} — ${workspaceAccess.titleText(title)}`]
91
+ if (collected.items.length === 0) {
92
+ lines.push('', 'No prior event matches found.')
93
+ return lines.join('\n')
94
+ }
95
+ lines.push('', `Event search results (${collected.items.length}):`)
96
+ for (const [index, hit] of collected.items.entries()) {
97
+ lines.push(
98
+ `${index + 1}. seq ${hit.seq} | ${hit.type} | ${hit.surface} | ${formatTime(hit.time)}`,
99
+ ` Snippet: ${hit.snippet}`,
100
+ )
101
+ }
102
+ if (collected.capped) {
103
+ lines.push('', 'Result cap reached. Narrow the query or add filters to find additional matches.')
104
+ }
105
+ return lines.join('\n')
106
+ }
107
+
108
+ function formatSessionTrace(
109
+ trace: SessionLineageTrace,
110
+ ancestors: readonly SessionRecord[],
111
+ ancestorBoundary: boolean,
112
+ descendants: AuthorizedDescendants,
113
+ titles: CompleteTitleMap,
114
+ ): string {
115
+ const lines = [
116
+ `Session ${trace.target.header.id} — ${workspaceAccess.titleText(titles.get(trace.target.header.id))}`,
117
+ `Created: ${formatTime(trace.target.header.createdAt)}`,
118
+ `Availability: ${availabilityText(trace.target)}`,
119
+ '',
120
+ 'Ancestors (nearest first):',
121
+ ]
122
+ if (ancestors.length === 0 && !ancestorBoundary) lines.push('- none (target is a root session)')
123
+ for (const record of ancestors) {
124
+ lines.push(`- ${record.header.id} — ${workspaceAccess.titleText(titles.get(record.header.id))} | ${formatTime(record.header.createdAt)} | ${availabilityText(record)}`)
125
+ }
126
+ if (ancestorBoundary) lines.push('- [outside workspace boundary]')
127
+ lines.push('', 'Descendants:')
128
+ if (descendants.length === 0) lines.push('- none')
129
+ else renderDescendants(lines, descendants, titles)
130
+ return lines.join('\n')
131
+ }
132
+
133
+ function renderDescendants(
134
+ lines: string[],
135
+ nodes: AuthorizedDescendants,
136
+ titles: CompleteTitleMap,
137
+ ): void {
138
+ for (const { node, depth } of workspaceAccess.visitDescendants(nodes)) {
139
+ const indent = ' '.repeat(depth)
140
+ if (node === null) {
141
+ lines.push(`${indent}- [outside workspace subtree]`)
142
+ continue
143
+ }
144
+ const id = node.record.header.id
145
+ lines.push(`${indent}- ${id} — ${workspaceAccess.titleText(titles.get(id))} | ${formatTime(node.record.header.createdAt)} | ${availabilityText(node.record)}`)
146
+ }
147
+ }
148
+
149
+ function formatEventTrace(
150
+ sessionId: SessionId,
151
+ title: TitleView,
152
+ trace: SessionEventTraceObservation,
153
+ ): string {
154
+ return [
155
+ `Session ${sessionId} — ${workspaceAccess.titleText(title)}`,
156
+ `Target: seq ${trace.target.seq} | ${trace.target.type} | ${trace.target.surface} | ${formatTime(trace.target.time)}`,
157
+ `Replaced by: ${trace.replacedBy ?? 'none'}`,
158
+ `Replacement chain: ${seqList(trace.replacementChain)}`,
159
+ `Events replaced by target: ${seqList(trace.replacedEventSeqs)}`,
160
+ `Events cited directly as sources: ${seqList(trace.sourceEventSeqs)}`,
161
+ `Direct derived events: ${seqList(trace.derivedEventSeqs)}`,
162
+ ].join('\n')
163
+ }
164
+
165
+ function formatEventRead(
166
+ sessionId: SessionId,
167
+ title: TitleView,
168
+ window: SessionEventWindow,
169
+ ): string {
170
+ const before = window.events.filter(event => event.seq < window.target.seq)
171
+ const after = window.events.filter(event => event.seq > window.target.seq)
172
+ const lines = [
173
+ `Session ${sessionId} — ${workspaceAccess.titleText(title)}`,
174
+ `Target event seq ${window.target.seq}:`,
175
+ '```json',
176
+ JSON.stringify(window.target, null, 2),
177
+ '```',
178
+ ]
179
+ if (before.length > 0) {
180
+ lines.push('', 'Before:')
181
+ for (const event of before) lines.push(formatNeighbor(event))
182
+ }
183
+ if (after.length > 0) {
184
+ lines.push('', 'After:')
185
+ for (const event of after) lines.push(formatNeighbor(event))
186
+ }
187
+ return lines.join('\n')
188
+ }
189
+
190
+ function formatNeighbor(event: SessionEvent): string {
191
+ const text = extractSessionEventText(event)
192
+ return `- seq ${event.seq} | ${event.type} | ${formatTime(event.time)}`
193
+ + (text.length === 0 ? ' | (no semantic text)' : `\n ${text.replaceAll('\n', '\n ')}`)
194
+ }
195
+
196
+ function availabilityText(record: SessionRecord): string {
197
+ return [
198
+ record.live ? 'live' : undefined,
199
+ record.persisted ? 'persisted' : undefined,
200
+ ].filter((value): value is string => value !== undefined).join(', ') || 'unavailable'
201
+ }
202
+
203
+ function seqList(values: readonly number[]): string {
204
+ return values.length === 0 ? 'none' : values.join(', ')
205
+ }
206
+
207
+ function formatTime(value: number): string {
208
+ return new Date(value).toISOString()
209
+ }
210
+
211
+ function presentSessionSearchCall(args: SessionSearchCallArgs): GenericCallView {
212
+ return { card: 'generic', kind: 'search', title: 'Search prior sessions', rawInput: args.query }
213
+ }
214
+
215
+ function presentEventSearchCall(args: EventSearchCallArgs): GenericCallView {
216
+ return { card: 'generic', kind: 'search', title: 'Search session events', rawInput: args.query }
217
+ }
218
+
219
+ function presentSessionTraceCall(args: SessionTargetCallArgs): GenericCallView {
220
+ return {
221
+ card: 'generic',
222
+ kind: 'read',
223
+ title: args.session_id === undefined ? 'Trace current session' : `Trace session ${args.session_id}`,
224
+ ...args.session_id === undefined ? {} : { rawInput: args.session_id },
225
+ }
226
+ }
227
+
228
+ function presentEventTargetCall(
229
+ action: string,
230
+ args: EventTargetCallArgs,
231
+ ): GenericCallView {
232
+ return {
233
+ card: 'generic',
234
+ kind: 'read',
235
+ title: `${action} ${args.seq}`,
236
+ rawInput: {
237
+ ...args.session_id === undefined ? {} : { session_id: args.session_id },
238
+ seq: args.seq,
239
+ },
240
+ }
241
+ }
242
+
243
+ /** Text output and call-card presentation for every session-query tool. */
244
+ export const presentation = {
245
+ formatSessionSearch,
246
+ formatEmptySessionSearch,
247
+ formatEventSearch,
248
+ formatSessionTrace,
249
+ formatEventTrace,
250
+ formatEventRead,
251
+ presentSessionSearchCall,
252
+ presentEventSearchCall,
253
+ presentSessionTraceCall,
254
+ presentEventTargetCall,
255
+ }
@@ -0,0 +1,179 @@
1
+ /**
2
+ * Session-query service error containment and model-safe translation.
3
+ *
4
+ * @module @unieai/rabi-tool-session-query/service-boundary
5
+ */
6
+
7
+ import type { Context } from '@unieai/cordis'
8
+ import { HarnessError } from '@unieai/rabi-llm'
9
+ import {
10
+ SessionQueryError,
11
+ type SessionQueryErrorCode,
12
+ } from '@unieai/rabi-session-query'
13
+
14
+ interface ModelSafeServiceFailure {
15
+ readonly code: SessionQueryErrorCode | 'SESSION_QUERY_TOOL_FAILED'
16
+ readonly message: string
17
+ }
18
+
19
+ const UNPRINTABLE_SERVICE_ERROR = '[unprintable session query failure]'
20
+
21
+ const SAFE_SESSION_QUERY_FAILURES = {
22
+ SESSION_QUERY_ABORTED: {
23
+ code: 'SESSION_QUERY_ABORTED',
24
+ message: 'session query was cancelled',
25
+ },
26
+ SESSION_QUERY_CORRUPT_SESSION: {
27
+ code: 'SESSION_QUERY_CORRUPT_SESSION',
28
+ message: 'session event history is corrupt',
29
+ },
30
+ SESSION_QUERY_EVENT_NOT_FOUND: {
31
+ code: 'SESSION_QUERY_EVENT_NOT_FOUND',
32
+ message: 'session event was not found',
33
+ },
34
+ SESSION_QUERY_INDEX_FAILED: {
35
+ code: 'SESSION_QUERY_INDEX_FAILED',
36
+ message: 'session search index is unavailable',
37
+ },
38
+ SESSION_QUERY_INVALID_CONFIG: {
39
+ code: 'SESSION_QUERY_TOOL_FAILED',
40
+ message: 'session query operation failed',
41
+ },
42
+ SESSION_QUERY_INVALID_CURSOR: {
43
+ code: 'SESSION_QUERY_INVALID_CURSOR',
44
+ message: 'session search continuation is invalid',
45
+ },
46
+ SESSION_QUERY_INVALID_FILTER: {
47
+ code: 'SESSION_QUERY_INVALID_FILTER',
48
+ message: 'session query filters were rejected',
49
+ },
50
+ SESSION_QUERY_INVALID_LIMIT: {
51
+ code: 'SESSION_QUERY_INVALID_LIMIT',
52
+ message: 'session query result limit was rejected',
53
+ },
54
+ SESSION_QUERY_INVALID_QUERY: {
55
+ code: 'SESSION_QUERY_INVALID_QUERY',
56
+ message: 'session query was rejected',
57
+ },
58
+ SESSION_QUERY_INVALID_LINEAGE: {
59
+ code: 'SESSION_QUERY_INVALID_LINEAGE',
60
+ message: 'session lineage is invalid',
61
+ },
62
+ SESSION_QUERY_INVALID_SURFACE: {
63
+ code: 'SESSION_QUERY_INVALID_SURFACE',
64
+ message: 'session event history is invalid',
65
+ },
66
+ SESSION_QUERY_INVALID_WINDOW: {
67
+ code: 'SESSION_QUERY_INVALID_WINDOW',
68
+ message: 'session event window is invalid',
69
+ },
70
+ SESSION_QUERY_PERSISTENCE_FAILED: {
71
+ code: 'SESSION_QUERY_PERSISTENCE_FAILED',
72
+ message: 'session history storage is unavailable',
73
+ },
74
+ SESSION_QUERY_SEARCH_DISABLED: {
75
+ code: 'SESSION_QUERY_SEARCH_DISABLED',
76
+ message: 'session search is disabled in this deployment',
77
+ },
78
+ SESSION_QUERY_SESSION_NOT_FOUND: {
79
+ code: 'SESSION_QUERY_SESSION_NOT_FOUND',
80
+ message: 'session was not found',
81
+ },
82
+ SESSION_QUERY_STALE_CURSOR: {
83
+ code: 'SESSION_QUERY_STALE_CURSOR',
84
+ message: 'session history changed while paging; retry the complete search call',
85
+ },
86
+ SESSION_QUERY_SOURCE_CONFLICT: {
87
+ code: 'SESSION_QUERY_TOOL_FAILED',
88
+ message: 'session query operation failed',
89
+ },
90
+ } satisfies Record<SessionQueryErrorCode, ModelSafeServiceFailure>
91
+
92
+ function unauthorizedTarget(): HarnessError {
93
+ return new HarnessError(
94
+ 'session target is outside the caller workspace',
95
+ 'SESSION_QUERY_TOOL_UNAUTHORIZED',
96
+ )
97
+ }
98
+
99
+ async function call<Value>(
100
+ ctx: Context,
101
+ signal: AbortSignal,
102
+ operation: string,
103
+ invoke: () => Promise<Value>,
104
+ ): Promise<Value> {
105
+ signal.throwIfAborted()
106
+ try {
107
+ const value = await invoke()
108
+ signal.throwIfAborted()
109
+ return value
110
+ } catch (error: unknown) {
111
+ signal.throwIfAborted()
112
+ throw sanitizeError(ctx, operation, error)
113
+ }
114
+ }
115
+
116
+ function sanitizeError(
117
+ ctx: Context,
118
+ operation: string,
119
+ error: unknown,
120
+ ): HarnessError {
121
+ const generic = genericFailure()
122
+ const diagnostic = fullError(error)
123
+ try {
124
+ ctx.logger.warn(`tool-session-query: ${operation} failed: ${diagnostic}`)
125
+ if (error instanceof SessionQueryError) {
126
+ const code: unknown = error.code
127
+ const failure = typeof code === 'string' && Object.hasOwn(SAFE_SESSION_QUERY_FAILURES, code)
128
+ ? SAFE_SESSION_QUERY_FAILURES[code as SessionQueryErrorCode]
129
+ : undefined
130
+ if (failure !== undefined && failure.code !== 'SESSION_QUERY_TOOL_FAILED') {
131
+ return new SessionQueryError(failure.message, failure.code)
132
+ }
133
+ }
134
+ if (error instanceof HarnessError && error.code === 'SESSION_QUERY_TOOL_UNAUTHORIZED') {
135
+ return unauthorizedTarget()
136
+ }
137
+ } catch {
138
+ return generic
139
+ }
140
+ return generic
141
+ }
142
+
143
+ function genericFailure(): HarnessError {
144
+ return new HarnessError(
145
+ 'session query operation failed',
146
+ 'SESSION_QUERY_TOOL_FAILED',
147
+ )
148
+ }
149
+
150
+ function fullError(error: unknown): string {
151
+ try {
152
+ return renderFullError(error)
153
+ } catch {
154
+ return UNPRINTABLE_SERVICE_ERROR
155
+ }
156
+ }
157
+
158
+ function renderFullError(error: unknown): string {
159
+ if (!(error instanceof Error)) return String(error)
160
+ const diagnostics: string[] = []
161
+ const seen = new Set<Error>()
162
+ let current: unknown = error
163
+ while (current instanceof Error && !seen.has(current)) {
164
+ seen.add(current)
165
+ diagnostics.push(current.stack ?? String(current))
166
+ current = current.cause
167
+ }
168
+ /* v8 ignore next -- defensive containment for a cyclic Error.cause graph */
169
+ if (current instanceof Error) diagnostics.push('[circular error cause]')
170
+ else if (current !== undefined) diagnostics.push(renderFullError(current))
171
+ return diagnostics.join('\nCaused by: ')
172
+ }
173
+
174
+ /** Model-safe session-query invocation and error translation boundary. */
175
+ export const serviceBoundary = {
176
+ unauthorizedTarget,
177
+ call,
178
+ sanitizeError,
179
+ }
@@ -0,0 +1,256 @@
1
+ /**
2
+ * Caller identity, workspace authorization, and visible lineage projection.
3
+ *
4
+ * @module @unieai/rabi-tool-session-query/workspace-access
5
+ */
6
+
7
+ import type { Context } from '@unieai/cordis'
8
+ import { brandString } from '@unieai/rabi-brand'
9
+ import { HarnessError } from '@unieai/rabi-llm'
10
+ import {
11
+ type SessionHeader,
12
+ type SessionId as SessionIdValue,
13
+ } from '@unieai/rabi-session'
14
+ import type { TurnBoundaryProjection } from '@unieai/rabi-agent'
15
+ import type {
16
+ SessionLineageNode,
17
+ SessionRecord,
18
+ } from '@unieai/rabi-session-query'
19
+ import type { ToolRunContext } from '@unieai/rabi-tools'
20
+ import { serviceBoundary } from './service-boundary.ts'
21
+
22
+ interface Caller {
23
+ readonly id: SessionIdValue
24
+ readonly header: SessionHeader
25
+ /** The caller's own-session boundary fold (the `turnBoundary` projection). */
26
+ readonly boundary: TurnBoundaryProjection
27
+ }
28
+
29
+ interface TitleView {
30
+ readonly text: string
31
+ readonly unavailableCode?: string
32
+ }
33
+
34
+ interface CompleteTitleMap extends ReadonlyMap<SessionIdValue, TitleView> {
35
+ get(id: SessionIdValue): TitleView
36
+ }
37
+
38
+ interface AuthorizedDescendant {
39
+ readonly record: SessionRecord
40
+ readonly descendants: Array<AuthorizedDescendant | null>
41
+ }
42
+
43
+ interface DescendantProjectionFrame {
44
+ readonly node: SessionLineageNode
45
+ readonly target: Array<AuthorizedDescendant | null>
46
+ readonly next: DescendantProjectionFrame | undefined
47
+ }
48
+
49
+ interface DescendantVisit {
50
+ readonly node: AuthorizedDescendant | null
51
+ readonly depth: number
52
+ readonly next: DescendantVisit | undefined
53
+ }
54
+
55
+ function callerOf(exec: ToolRunContext, ctx: Context): Caller {
56
+ const agent = exec.agent
57
+ if (agent === undefined) {
58
+ throw new HarnessError(
59
+ 'session query tools require an agent-bound caller',
60
+ 'SESSION_QUERY_TOOL_MISSING_AGENT',
61
+ )
62
+ }
63
+ return {
64
+ id: agent.session.id,
65
+ header: agent.session.header,
66
+ boundary: ctx.agents.turnBoundaryOf(agent.session),
67
+ }
68
+ }
69
+
70
+ function targetId(args: { readonly session_id?: string }, caller: Caller): SessionIdValue {
71
+ return args.session_id === undefined ? caller.id : brandString<SessionIdValue>(args.session_id)
72
+ }
73
+
74
+ async function authorizeTarget(
75
+ ctx: Context,
76
+ caller: Caller,
77
+ target: SessionIdValue,
78
+ signal: AbortSignal,
79
+ ): Promise<void> {
80
+ if (target === caller.id) return
81
+ const cwd = caller.header.cwd
82
+ if (cwd === undefined) throw serviceBoundary.unauthorizedTarget()
83
+ const records = await serviceBoundary.call(ctx, signal, 'target authorization', () =>
84
+ ctx.sessionQuery.filterSessions([
85
+ { kind: 'id', values: [target] },
86
+ { kind: 'cwd', values: [cwd] },
87
+ ], signal))
88
+ if (records.length !== 1) throw serviceBoundary.unauthorizedTarget()
89
+ }
90
+
91
+ function recordAuthorized(record: SessionRecord, caller: Caller): boolean {
92
+ return headerAuthorized(record.header, caller)
93
+ }
94
+
95
+ function headerAuthorized(header: SessionHeader, caller: Caller): boolean {
96
+ if (header.id === caller.id) return header.cwd === caller.header.cwd
97
+ return caller.header.cwd !== undefined && header.cwd === caller.header.cwd
98
+ }
99
+
100
+ function assertObservedTargetAuthorized(
101
+ caller: Caller,
102
+ target: SessionIdValue,
103
+ observed: SessionHeader,
104
+ ): void {
105
+ if (observed.id !== target || !headerAuthorized(observed, caller)) {
106
+ throw serviceBoundary.unauthorizedTarget()
107
+ }
108
+ }
109
+
110
+ async function authorizeSessionIds(
111
+ ctx: Context,
112
+ caller: Caller,
113
+ ids: readonly SessionIdValue[],
114
+ signal: AbortSignal,
115
+ ): Promise<ReadonlySet<SessionIdValue>> {
116
+ const unique = [...new Set(ids)]
117
+ const authorized = new Set<SessionIdValue>()
118
+ if (unique.includes(caller.id)) authorized.add(caller.id)
119
+ const cwd = caller.header.cwd
120
+ const other = unique.filter(id => id !== caller.id)
121
+ if (cwd === undefined || other.length === 0) return authorized
122
+ const records = await serviceBoundary.call(ctx, signal, 'session-id authorization', () =>
123
+ ctx.sessionQuery.filterSessions([
124
+ { kind: 'id', values: other },
125
+ { kind: 'cwd', values: [cwd] },
126
+ ], signal))
127
+ const requested = new Set(other)
128
+ for (const record of records) {
129
+ if (requested.has(record.header.id) && recordAuthorized(record, caller)) {
130
+ authorized.add(record.header.id)
131
+ }
132
+ }
133
+ return authorized
134
+ }
135
+
136
+ async function readTitles(
137
+ ctx: Context,
138
+ caller: Caller,
139
+ ids: readonly SessionIdValue[],
140
+ signal: AbortSignal,
141
+ ): Promise<CompleteTitleMap> {
142
+ const result = new Map<SessionIdValue, TitleView>()
143
+ const observations = await serviceBoundary.call(ctx, signal, 'title observation', () =>
144
+ ctx.sessionQuery.readTitleSnapshots(ids, signal))
145
+ for (const observation of observations) {
146
+ if (observation.status === 'rejected') {
147
+ result.set(observation.sessionId, unavailableTitle(ctx, observation.reason))
148
+ continue
149
+ }
150
+ assertObservedTargetAuthorized(caller, observation.sessionId, observation.value.session)
151
+ result.set(observation.sessionId, { text: observation.value.title?.title ?? 'untitled' })
152
+ }
153
+ return result as CompleteTitleMap
154
+ }
155
+
156
+ async function readTitle(
157
+ ctx: Context,
158
+ caller: Caller,
159
+ id: SessionIdValue,
160
+ signal: AbortSignal,
161
+ ): Promise<TitleView> {
162
+ return (await readTitles(ctx, caller, [id], signal)).get(id)
163
+ }
164
+
165
+ function unavailableTitle(
166
+ ctx: Context,
167
+ error: unknown,
168
+ ): TitleView {
169
+ const sanitized = serviceBoundary.sanitizeError(ctx, 'title observation item', error)
170
+ if (sanitized.code === 'SESSION_QUERY_TOOL_UNAUTHORIZED') throw sanitized
171
+ return { text: 'untitled', unavailableCode: sanitized.code }
172
+ }
173
+
174
+ function authorizeDescendants(
175
+ nodes: readonly SessionLineageNode[],
176
+ caller: Caller,
177
+ ): Array<AuthorizedDescendant | null> {
178
+ const result: Array<AuthorizedDescendant | null> = []
179
+ let pending: DescendantProjectionFrame | undefined
180
+ for (const node of [...nodes].reverse()) {
181
+ pending = { node, target: result, next: pending }
182
+ }
183
+ while (pending !== undefined) {
184
+ const current = pending
185
+ pending = current.next
186
+ if (!recordAuthorized(current.node.session, caller)) {
187
+ current.target.push(null)
188
+ continue
189
+ }
190
+ const projected: AuthorizedDescendant = {
191
+ record: current.node.session,
192
+ descendants: [],
193
+ }
194
+ current.target.push(projected)
195
+ for (const child of [...current.node.descendants].reverse()) {
196
+ pending = {
197
+ node: child,
198
+ target: projected.descendants,
199
+ next: pending,
200
+ }
201
+ }
202
+ }
203
+ return result
204
+ }
205
+
206
+ function * visitDescendants(
207
+ nodes: readonly (AuthorizedDescendant | null)[],
208
+ ): Generator<DescendantVisit> {
209
+ let pending: DescendantVisit | undefined
210
+ for (const node of [...nodes].reverse()) {
211
+ pending = { node, depth: 0, next: pending }
212
+ }
213
+ while (pending !== undefined) {
214
+ const current = pending
215
+ pending = current.next
216
+ yield current
217
+ if (current.node === null) continue
218
+ for (const child of [...current.node.descendants].reverse()) {
219
+ pending = {
220
+ node: child,
221
+ depth: current.depth + 1,
222
+ next: pending,
223
+ }
224
+ }
225
+ }
226
+ }
227
+
228
+ function descendantIds(nodes: readonly (AuthorizedDescendant | null)[]): SessionIdValue[] {
229
+ const ids: SessionIdValue[] = []
230
+ for (const { node } of visitDescendants(nodes)) {
231
+ if (node !== null) ids.push(node.record.header.id)
232
+ }
233
+ return ids
234
+ }
235
+
236
+ function titleText(view: TitleView): string {
237
+ return view.unavailableCode === undefined
238
+ ? view.text
239
+ : `${view.text} (title unavailable: ${view.unavailableCode})`
240
+ }
241
+
242
+ /** Workspace-scoped caller authorization, title access, and lineage projection. */
243
+ export const workspaceAccess = {
244
+ callerOf,
245
+ targetId,
246
+ authorizeTarget,
247
+ recordAuthorized,
248
+ assertObservedTargetAuthorized,
249
+ authorizeSessionIds,
250
+ readTitles,
251
+ readTitle,
252
+ authorizeDescendants,
253
+ visitDescendants,
254
+ descendantIds,
255
+ titleText,
256
+ }