dsh-ocean-background 0.0.0-stage → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/THIRD_PARTY_NOTICES.md +30 -0
  2. package/client.js +582 -0
  3. package/docs/DETAIL.md +37 -0
  4. package/host/fork-snapshots.js +60 -0
  5. package/host/session-facts.js +205 -0
  6. package/host/session-state.js +383 -0
  7. package/icon.svg +19 -0
  8. package/index.js +299 -0
  9. package/locale/en.json +7 -0
  10. package/locale/zh.json +7 -0
  11. package/mileage.js +312 -0
  12. package/package.json +35 -4
  13. package/runtime/assets/coconut-palm.glb +0 -0
  14. package/runtime/assets/dinghy.glb +0 -0
  15. package/runtime/assets/ship.glb +0 -0
  16. package/runtime/boats.js +199 -0
  17. package/runtime/fleet.js +260 -0
  18. package/runtime/glsl.js +60 -0
  19. package/runtime/index.html +22 -0
  20. package/runtime/lifecycle.js +94 -0
  21. package/runtime/main.js +615 -0
  22. package/runtime/ocean.js +192 -0
  23. package/runtime/resources.js +27 -0
  24. package/runtime/scenery-geometry.js +363 -0
  25. package/runtime/scenery-layout.js +147 -0
  26. package/runtime/scenery.js +300 -0
  27. package/runtime/ship.js +272 -0
  28. package/runtime/sky.js +64 -0
  29. package/runtime/state.js +362 -0
  30. package/runtime/style.css +45 -0
  31. package/runtime/vendor/THREE-LICENSE.txt +21 -0
  32. package/runtime/vendor/jsm/loaders/GLTFLoader.js +4890 -0
  33. package/runtime/vendor/jsm/utils/BufferGeometryUtils.js +1435 -0
  34. package/runtime/vendor/three.core.js +58773 -0
  35. package/runtime/vendor/three.module.js +18251 -0
  36. package/runtime/voyage.js +160 -0
  37. package/runtime/wave-field.js +125 -0
  38. package/runtime/wind-motion.js +93 -0
  39. package/runtime/wind.js +139 -0
  40. package/runtime/world-motion.js +24 -0
  41. package/README.md +0 -3
@@ -0,0 +1,60 @@
1
+ // The host integration for fork-time mileage snapshots is isolated here.
2
+ import { readService, notifyOnce, logOnce, describeError, resolveMileageTarget } from './session-state.js'
3
+
4
+ const FORK_OWNER = Symbol.for('ocean-background.fork-snapshot')
5
+ const SNAPSHOT_TIMEOUT_MS = 4000
6
+
7
+ export function installForkSnapshots(ctx, ledger) {
8
+ const controller = readService(ctx, 'sessionController')
9
+ if (!controller || typeof controller.fork !== 'function') {
10
+ notifyOnce(ctx, 'warn', 'fork-snapshot', 'ocean-background: sessionController.fork is unavailable; fork mileage cannot be inherited')
11
+ return () => {}
12
+ }
13
+ const previous = controller[FORK_OWNER]
14
+ if (typeof previous === 'function') {
15
+ try { previous() } catch {}
16
+ }
17
+ const original = controller.fork
18
+ const hadOwn = Object.hasOwn(controller, 'fork')
19
+ const wrapper = async function forkWithMileage(request) {
20
+ let token = null
21
+ try {
22
+ const source = typeof request?.sessionId === 'string' ? request.sessionId : null
23
+ if (source !== null) {
24
+ const target = await resolveMileageTarget(ctx, ledger, source, AbortSignal.timeout(SNAPSHOT_TIMEOUT_MS))
25
+ if (target.eligible) token = await ledger.beginFork(target.rootId)
26
+ }
27
+ } catch (error) {
28
+ logOnce(ctx, 'warn', 'fork-snapshot', `ocean-background: fork mileage snapshot failed: ${describeError(error)}`)
29
+ }
30
+ const value = await original.call(this, request)
31
+ try {
32
+ if (token && value && typeof value.sessionId === 'string') {
33
+ await ledger.settleFork(token, value.sessionId)
34
+ }
35
+ } catch (error) {
36
+ logOnce(ctx, 'warn', 'fork-snapshot', `ocean-background: fork mileage record failed: ${describeError(error)}`)
37
+ }
38
+ return value
39
+ }
40
+ try {
41
+ controller.fork = wrapper
42
+ } catch (error) {
43
+ logOnce(ctx, 'warn', 'fork-snapshot', `ocean-background: sessionController.fork cannot be wrapped: ${describeError(error)}`)
44
+ return () => {}
45
+ }
46
+ if (controller.fork !== wrapper) {
47
+ notifyOnce(ctx, 'warn', 'fork-snapshot', 'ocean-background: sessionController.fork is read-only; fork mileage cannot be inherited')
48
+ return () => {}
49
+ }
50
+ const restore = () => {
51
+ if (controller.fork === wrapper) {
52
+ if (hadOwn) controller.fork = original
53
+ else delete controller.fork
54
+ }
55
+ if (controller[FORK_OWNER] === restore) delete controller[FORK_OWNER]
56
+ }
57
+ controller[FORK_OWNER] = restore
58
+ return restore
59
+ }
60
+
@@ -0,0 +1,205 @@
1
+ // Pure folding of durable session events into token, turn and metering facts.
2
+
3
+ /** The one status vocabulary the renderer knows how to turn into a hull state. */
4
+ export const STATUS = Object.freeze({
5
+ working: 'working',
6
+ waiting: 'waiting',
7
+ completed: 'completed',
8
+ failed: 'failed',
9
+ cancelled: 'cancelled',
10
+ unavailable: 'unavailable',
11
+ })
12
+
13
+ const BUCKET_KEYS = Object.freeze([
14
+ 'uncachedInputTokens',
15
+ 'outputTokens',
16
+ 'cacheReadTokens',
17
+ 'cacheWriteTokens',
18
+ ])
19
+
20
+ const ZERO_BUCKETS = Object.freeze({
21
+ uncachedInputTokens: 0,
22
+ outputTokens: 0,
23
+ cacheReadTokens: 0,
24
+ cacheWriteTokens: 0,
25
+ })
26
+
27
+ export function countOf(value) {
28
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.trunc(value) : 0
29
+ }
30
+
31
+ function sameBuckets(left, right) {
32
+ return BUCKET_KEYS.every((key) => left[key] === right[key])
33
+ }
34
+
35
+ export function sumBuckets(buckets) {
36
+ let total = 0
37
+ for (const key of BUCKET_KEYS) {
38
+ const value = buckets?.[key]
39
+ if (typeof value === 'number' && Number.isFinite(value)) total += value
40
+ }
41
+ return total
42
+ }
43
+
44
+ /** The last `usage` chunk of one compact Assistant stream, read as plain JSON. */
45
+ function lastStreamUsage(stream) {
46
+ if (!Array.isArray(stream)) return undefined
47
+ for (let index = stream.length - 1; index >= 0; index -= 1) {
48
+ const record = stream[index]
49
+ if (record?.type !== 'chunk') continue
50
+ const chunk = record.chunk
51
+ if (chunk?.type === 'usage') return chunk.usage
52
+ }
53
+ return undefined
54
+ }
55
+
56
+ /**
57
+ * The usage sample one durable settlement reports, mirroring the tokenUsage fold:
58
+ * an explicit `data.usage` wins, otherwise the stream's last `usage` chunk.
59
+ */
60
+ export function usageOfEvent(event) {
61
+ const data = event?.data
62
+ if (!data || typeof data !== 'object') return undefined
63
+ if (event.type === 'assistant/message' && data.usage !== undefined) return data.usage
64
+ if (event.type !== 'assistant/message' && event.type !== 'assistant/attempt') return undefined
65
+ return lastStreamUsage(data.stream)
66
+ }
67
+
68
+ /**
69
+ * Map provider usage onto the four buckets the tokenUsage projection publishes.
70
+ * Raw `TokenUsage.inputTokens` is the uncached prompt count.
71
+ */
72
+ export function bucketsOf(usage) {
73
+ const pick = (key) => {
74
+ const value = usage?.[key]
75
+ return typeof value === 'number' && Number.isFinite(value) ? value : 0
76
+ }
77
+ return {
78
+ uncachedInputTokens: pick('inputTokens'),
79
+ outputTokens: pick('outputTokens'),
80
+ cacheReadTokens: pick('cacheReadTokens'),
81
+ cacheWriteTokens: pick('cacheWriteTokens'),
82
+ }
83
+ }
84
+
85
+ /** One fold state for a Session that has not been read yet. */
86
+ export function createFoldState() {
87
+ return {
88
+ readable: false,
89
+ inheritedEventCount: 0,
90
+ foldedThrough: -1,
91
+ buckets: { ...ZERO_BUCKETS },
92
+ lastUsage: null,
93
+ turnOpen: false,
94
+ lastTurnEnd: null,
95
+ firstUserAt: null,
96
+ }
97
+ }
98
+
99
+ function resetFoldState(state, inheritedEventCount) {
100
+ state.inheritedEventCount = inheritedEventCount
101
+ state.foldedThrough = inheritedEventCount - 1
102
+ state.buckets = { ...ZERO_BUCKETS }
103
+ state.lastUsage = null
104
+ state.turnOpen = false
105
+ state.lastTurnEnd = null
106
+ state.firstUserAt = null
107
+ }
108
+
109
+ /** Read one event without copying the log; the cursor keeps this at O(new events). */
110
+ function eventAtOf(session, seq) {
111
+ if (typeof session?.eventAt === 'function') return session.eventAt(seq)
112
+ if (typeof session?.snapshotEvents === 'function') return session.snapshotEvents(seq, seq + 1)[0]
113
+ return undefined
114
+ }
115
+
116
+ /** Fold one committed event, following the tokenUsage projection's replace and retry rules. */
117
+ function applyEventFacts(state, event) {
118
+ const type = event?.type
119
+ if (type === 'turn/start') {
120
+ state.turnOpen = true
121
+ return
122
+ }
123
+ if (type === 'turn/end') {
124
+ state.turnOpen = false
125
+ const kind = event.data?.reason?.kind
126
+ state.lastTurnEnd = typeof kind === 'string' ? kind : null
127
+ return
128
+ }
129
+ if (type === 'llm/retry-started') {
130
+ const data = event.data
131
+ if (state.lastUsage !== null
132
+ && state.lastUsage.turn === data?.turn
133
+ && state.lastUsage.step === data?.step) state.lastUsage = null
134
+ return
135
+ }
136
+ if (type === 'user/message') {
137
+ const kind = event.data?.source?.kind
138
+ if (state.firstUserAt === null
139
+ && event.surfaceOp === 'append'
140
+ && event.data?.role === 'user'
141
+ && (kind === 'user' || kind === 'user-rpc')) {
142
+ state.firstUserAt = typeof event.time === 'number' && Number.isFinite(event.time) ? event.time : 0
143
+ }
144
+ return
145
+ }
146
+ if (type !== 'assistant/message' && type !== 'assistant/attempt') return
147
+ const usage = usageOfEvent(event)
148
+ if (usage === undefined || usage === null) return
149
+ const data = event.data
150
+ const buckets = bucketsOf(usage)
151
+ const previous = state.lastUsage !== null
152
+ && state.lastUsage.turn === data?.turn
153
+ && state.lastUsage.step === data?.step
154
+ ? state.lastUsage.buckets
155
+ : undefined
156
+ if (previous !== undefined && sameBuckets(previous, buckets)) return
157
+ for (const key of BUCKET_KEYS) state.buckets[key] += buckets[key] - (previous?.[key] ?? 0)
158
+ state.lastUsage = { turn: data?.turn, step: data?.step, buckets }
159
+ }
160
+
161
+ /**
162
+ * Advance one Session's facts through its own events, starting at the fork cut.
163
+ *
164
+ * The tokenUsage projection folds the whole log, so a fork-seeded child's totals
165
+ * include the inherited prefix; this fold skips it and reads only events past the
166
+ * cursor. A gap throws, because a partial fold is not a complete read.
167
+ */
168
+ export function foldSessionFacts(state, session) {
169
+ const inherited = countOf(session?.inheritedEventCount)
170
+ const end = countOf(session?.seq)
171
+ if (state.inheritedEventCount !== inherited
172
+ || state.foldedThrough >= end
173
+ || state.foldedThrough < inherited - 1) {
174
+ resetFoldState(state, inherited)
175
+ }
176
+ for (let seq = state.foldedThrough + 1; seq < end; seq += 1) {
177
+ const event = eventAtOf(session, seq)
178
+ if (event === undefined || event === null) {
179
+ throw new Error(`session "${session?.id ?? ''}" has no event at seq ${String(seq)}`)
180
+ }
181
+ applyEventFacts(state, event)
182
+ state.foldedThrough = seq
183
+ }
184
+ state.readable = true
185
+ return state
186
+ }
187
+
188
+ /**
189
+ * Turn one Session's facts into the shared status word.
190
+ *
191
+ * A closed Turn is the only terminal evidence accepted here: a normal close
192
+ * completes a one-shot child and leaves a continuable child waiting, an abort or
193
+ * interruption cancels, an error or token ceiling fails. `blocked`, an unclosed
194
+ * turn, and an unread Session stay `waiting`; inactive proves nothing.
195
+ */
196
+ export function statusOfFacts(facts, mode) {
197
+ if (!facts || facts.readable !== true) return STATUS.unavailable
198
+ if (facts.turnOpen === true) return STATUS.working
199
+ const kind = facts.lastTurnEnd
200
+ if (kind === 'completed') return mode === 'one-shot' ? STATUS.completed : STATUS.waiting
201
+ if (kind === 'aborted' || kind === 'interrupted') return STATUS.cancelled
202
+ if (kind === 'error' || kind === 'max-tokens') return STATUS.failed
203
+ return STATUS.waiting
204
+ }
205
+
@@ -0,0 +1,383 @@
1
+ // Host-owned session reading. Each Cordis context owns its caches and diagnostics.
2
+ import { STATUS, sumBuckets, createFoldState, foldSessionFacts, statusOfFacts } from './session-facts.js'
3
+
4
+ /** `SessionHeader.origin` marks a Session created as a subagent child. */
5
+ const SUBAGENT_ORIGIN = 'subagent'
6
+ /** Bound for one upward walk; a cycle or a deep tree stops instead of looping. */
7
+ const MAX_ANCESTRY_DEPTH = 64
8
+ /** A cold Session is re-read from persistence at most once per window. */
9
+ const COLD_READ_TTL_MS = 1500
10
+ /** Header reads are cheap but not free; ancestry reuses them briefly. */
11
+ const HEADER_TTL_MS = 5000
12
+ /** Upper bound on retained per-Session fold state. */
13
+ const MAX_CACHE_ENTRIES = 256
14
+ /** Fold state untouched for this long is dropped. */
15
+ const CACHE_IDLE_MS = 120_000
16
+ /** Repeated failures log once per window instead of once per poll. */
17
+ const LOG_INTERVAL_MS = 10_000
18
+ const MAX_LOG_KEYS = 64
19
+
20
+ let states = new WeakMap()
21
+
22
+ function stateOf(ctx) {
23
+ let state = states.get(ctx)
24
+ if (state === undefined) {
25
+ state = { sessionCache: new Map(), headerCache: new Map(), inflight: new Map(), logTimes: new Map(), notified: new Set() }
26
+ states.set(ctx, state)
27
+ }
28
+ return state
29
+ }
30
+
31
+ export function readService(ctx, key) {
32
+ try {
33
+ if (typeof ctx.get === 'function') return ctx.get(key)
34
+ if (ctx.reflect && typeof ctx.reflect.get === 'function') return ctx.reflect.get(key)
35
+ } catch {}
36
+ return undefined
37
+ }
38
+
39
+ export function describeError(error) {
40
+ try {
41
+ return error instanceof Error ? error.message : String(error)
42
+ } catch {
43
+ return 'unrenderable error'
44
+ }
45
+ }
46
+
47
+ function logNow(ctx, level, message) {
48
+ try {
49
+ const logger = ctx?.logger
50
+ const method = logger?.[level] ?? logger?.info
51
+ if (typeof method === 'function') method.call(logger, message)
52
+ else if (typeof logger === 'function') logger.call(ctx, message)
53
+ } catch {}
54
+ }
55
+
56
+ export function logOnce(ctx, level, key, message) {
57
+ const { logTimes } = stateOf(ctx)
58
+ const now = Date.now()
59
+ const previous = logTimes.get(key)
60
+ if (previous !== undefined && now - previous < LOG_INTERVAL_MS) return
61
+ if (logTimes.size >= MAX_LOG_KEYS && !logTimes.has(key)) logTimes.clear()
62
+ logTimes.set(key, now)
63
+ logNow(ctx, level, message)
64
+ }
65
+
66
+ export function notifyOnce(ctx, level, key, message) {
67
+ const { notified } = stateOf(ctx)
68
+ if (notified.has(key)) return
69
+ notified.add(key)
70
+ logNow(ctx, level, message)
71
+ }
72
+
73
+ function disposeObservation(observation) {
74
+ if (!observation) return
75
+ try {
76
+ const asyncDispose = observation[Symbol.asyncDispose]
77
+ if (typeof asyncDispose === 'function') {
78
+ Promise.resolve(asyncDispose.call(observation)).catch(() => {})
79
+ return
80
+ }
81
+ const syncDispose = observation[Symbol.dispose]
82
+ if (typeof syncDispose === 'function') syncDispose.call(observation)
83
+ else if (typeof observation.dispose === 'function') observation.dispose()
84
+ } catch {}
85
+ }
86
+
87
+ function cacheEntry(ctx, sessionId) {
88
+ const { sessionCache } = stateOf(ctx)
89
+ let entry = sessionCache.get(sessionId)
90
+ if (entry === undefined) {
91
+ entry = { at: 0, state: createFoldState() }
92
+ sessionCache.set(sessionId, entry)
93
+ }
94
+ return entry
95
+ }
96
+
97
+ function pruneCache(ctx, now) {
98
+ const { sessionCache, headerCache } = stateOf(ctx)
99
+ for (const [sessionId, entry] of sessionCache) {
100
+ if (entry.at !== 0 && now - entry.at > CACHE_IDLE_MS) sessionCache.delete(sessionId)
101
+ }
102
+ for (const [sessionId, entry] of headerCache) {
103
+ if (now - entry.at > CACHE_IDLE_MS) headerCache.delete(sessionId)
104
+ }
105
+ if (sessionCache.size > MAX_CACHE_ENTRIES) {
106
+ const oldest = [...sessionCache.entries()].sort((left, right) => left[1].at - right[1].at)
107
+ for (const [sessionId] of oldest) {
108
+ if (sessionCache.size <= MAX_CACHE_ENTRIES) break
109
+ sessionCache.delete(sessionId)
110
+ }
111
+ }
112
+ if (headerCache.size > MAX_CACHE_ENTRIES) {
113
+ const oldest = [...headerCache.entries()].sort((left, right) => left[1].at - right[1].at)
114
+ for (const [sessionId] of oldest) {
115
+ if (headerCache.size <= MAX_CACHE_ENTRIES) break
116
+ headerCache.delete(sessionId)
117
+ }
118
+ }
119
+ }
120
+
121
+ /** Drop every retained Session fact and header. Called when the plugin unloads. */
122
+ export function clearOceanCaches(ctx) {
123
+ if (ctx === undefined) states = new WeakMap()
124
+ else states.delete(ctx)
125
+ }
126
+
127
+ function liveSession(ctx, sessionId) {
128
+ const sessions = readService(ctx, 'sessions')
129
+ if (!sessions || typeof sessions.get !== 'function') return undefined
130
+ try {
131
+ return sessions.get(sessionId)
132
+ } catch {
133
+ return undefined
134
+ }
135
+ }
136
+
137
+ /**
138
+ * Read one Session's own-suffix facts.
139
+ *
140
+ * A live Session folds in place. A cold one goes through `sessionQuery.inspectSession`,
141
+ * which reuses or restores a prepared Session without publishing it; the result is
142
+ * reused for a short window with one shared pass. Failure returns null.
143
+ */
144
+ export async function readSessionFacts(ctx, sessionId, signal) {
145
+ const { inflight } = stateOf(ctx)
146
+ const live = liveSession(ctx, sessionId)
147
+ const entry = cacheEntry(ctx, sessionId)
148
+ if (live !== undefined) {
149
+ try {
150
+ const state = foldSessionFacts(entry.state, live)
151
+ entry.at = Date.now()
152
+ return state
153
+ } catch (error) {
154
+ entry.at = Date.now()
155
+ entry.state.readable = false
156
+ logOnce(ctx, 'warn', `facts:${sessionId}`, `ocean-background: folding live session "${sessionId}" failed: ${describeError(error)}`)
157
+ return null
158
+ }
159
+ }
160
+
161
+ const now = Date.now()
162
+ // A zero timestamp means this Session has never been read. A later timestamp
163
+ // covers both a fresh success and a failed attempt backing off for the window.
164
+ if (entry.at !== 0 && now - entry.at < COLD_READ_TTL_MS) {
165
+ return entry.state.readable ? entry.state : null
166
+ }
167
+
168
+ const pending = inflight.get(sessionId)
169
+ if (pending !== undefined) return pending
170
+
171
+ const query = readService(ctx, 'sessionQuery')
172
+ if (!query || typeof query.inspectSession !== 'function') {
173
+ notifyOnce(ctx, 'warn', 'session-query', 'ocean-background: sessionQuery.inspectSession is unavailable; fleet tokens cannot be read')
174
+ return null
175
+ }
176
+
177
+ const read = query.inspectSession(
178
+ sessionId,
179
+ (session) => foldSessionFacts(entry.state, session),
180
+ signal,
181
+ )
182
+ const task = Promise.resolve(read).then((state) => {
183
+ entry.at = Date.now()
184
+ return state
185
+ }).catch((error) => {
186
+ entry.at = Date.now()
187
+ entry.state.readable = false
188
+ logOnce(ctx, 'warn', `facts:${sessionId}`, `ocean-background: reading session "${sessionId}" failed: ${describeError(error)}`)
189
+ return null
190
+ }).finally(() => {
191
+ if (inflight.get(sessionId) === task) inflight.delete(sessionId)
192
+ })
193
+ inflight.set(sessionId, task)
194
+ return task
195
+ }
196
+
197
+ /**
198
+ * Read one Session's immutable header, live first, then from a cold head read
199
+ * that computes no projections.
200
+ */
201
+ async function readHeader(ctx, sessionId, signal) {
202
+ const { headerCache } = stateOf(ctx)
203
+ const live = liveSession(ctx, sessionId)
204
+ if (live?.header) return live.header
205
+ const cached = headerCache.get(sessionId)
206
+ const now = Date.now()
207
+ if (cached !== undefined && now - cached.at < HEADER_TTL_MS) return cached.header
208
+
209
+ const query = readService(ctx, 'sessionQuery')
210
+ if (!query || typeof query.observeSession !== 'function') return null
211
+ const observation = await query.observeSession(sessionId, { signal, projectionMode: 'none' })
212
+ try {
213
+ const header = observation?.header ?? null
214
+ if (header) headerCache.set(sessionId, { at: Date.now(), header })
215
+ return header
216
+ } finally {
217
+ disposeObservation(observation)
218
+ }
219
+ }
220
+
221
+ /**
222
+ * Resolve the conversation root for a selection.
223
+ *
224
+ * Only `origin: 'subagent'` makes a Session a child; an ordinary fork may keep
225
+ * `parentSession` and stays its own root. A broken chain is an error, never a
226
+ * child reported as the root it failed to find.
227
+ */
228
+ export async function resolveRootSessionId(ctx, sessionId, signal) {
229
+ let current = sessionId
230
+ const visited = new Set()
231
+ for (let depth = 0; depth < MAX_ANCESTRY_DEPTH; depth += 1) {
232
+ if (visited.has(current)) throw new Error(`session ancestry is cyclic at "${current}"`)
233
+ visited.add(current)
234
+ const header = await readHeader(ctx, current, signal)
235
+ if (header === null) throw new Error(`session "${current}" has no readable header`)
236
+ if (header.origin !== SUBAGENT_ORIGIN) return current
237
+ const parent = header.parentSession
238
+ if (typeof parent !== 'string' || parent === '') {
239
+ throw new Error(`subagent session "${current}" has no parentSession`)
240
+ }
241
+ current = parent
242
+ }
243
+ throw new Error(`session ancestry exceeds ${String(MAX_ANCESTRY_DEPTH)} levels at "${current}"`)
244
+ }
245
+
246
+ export function isMeteringEligible(facts, hasForkBase = false) {
247
+ if (!facts || facts.readable !== true) return false
248
+ return facts.firstUserAt !== null || hasForkBase === true
249
+ }
250
+
251
+ export async function resolveMileageTarget(ctx, ledger, selected, signal) {
252
+ if (typeof selected !== 'string' || selected.trim() === '') {
253
+ return { rootId: null, eligible: false }
254
+ }
255
+ const rootId = await resolveRootSessionId(ctx, selected.trim(), signal)
256
+ await ledger.ready()
257
+ const facts = await readSessionFacts(ctx, rootId, signal)
258
+ return { rootId, eligible: isMeteringEligible(facts, ledger.hasForkRoot(rootId)) }
259
+ }
260
+
261
+ function rowIdOf(row) {
262
+ const id = row?.id ?? row?.sessionId ?? row?.childId
263
+ return typeof id === 'string' && id !== '' ? id : null
264
+ }
265
+
266
+ function rowTitleOf(row) {
267
+ const name = typeof row?.name === 'string' ? row.name : ''
268
+ if (name !== '') return name
269
+ const label = typeof row?.label === 'string' ? row.label : ''
270
+ return label
271
+ }
272
+
273
+ function childRow(id, status, title) {
274
+ const row = { id, running: status === STATUS.working, status }
275
+ if (title !== '') row.title = title
276
+ return row
277
+ }
278
+
279
+ /**
280
+ * List every descendant through the durable subagent catalogs, which walk the
281
+ * whole tree without loading an Agent. A throwing listing stays an error; it is
282
+ * never replaced by direct children alone.
283
+ */
284
+ export async function listFleetRows(ctx, rootId, signal) {
285
+ const subagents = readService(ctx, 'subagents')
286
+ if (!subagents || typeof subagents.listDescendants !== 'function') {
287
+ notifyOnce(ctx, 'info', 'subagents', 'ocean-background: subagents service is not mounted; the fleet shows the root only')
288
+ return []
289
+ }
290
+ const listed = await subagents.listDescendants(rootId, signal)
291
+ if (!Array.isArray(listed)) throw new Error('subagent listing returned no rows')
292
+ return listed
293
+ }
294
+
295
+ /** The response for a missing selection: no conversation, no boats, no guess. */
296
+ export function emptySnapshot() {
297
+ return {
298
+ ok: true,
299
+ sessionId: null,
300
+ tokensComplete: true,
301
+ totalTokens: 0,
302
+ flowTokens: 0,
303
+ agentRunning: false,
304
+ children: [],
305
+ }
306
+ }
307
+
308
+ /**
309
+ * Build one state payload for a selected main-view Session.
310
+ *
311
+ * Tokens are the four real usage buckets over the root and every distinct
312
+ * descendant, each counted once because every fold starts at its own fork cut.
313
+ * `flowTokens` repeats the cumulative total the renderer turns into a delta. An
314
+ * unreadable branch makes the total unknowable: `tokensComplete: false` with null
315
+ * counters, so a partial sum never reads as a lull and then a spike.
316
+ */
317
+ export async function sessionSnapshot(ctx, sessionId, signal) {
318
+ if (typeof sessionId !== 'string' || sessionId.trim() === '') return emptySnapshot()
319
+ const selected = sessionId.trim()
320
+ pruneCache(ctx, Date.now())
321
+ const rootId = await resolveRootSessionId(ctx, selected, signal)
322
+ const rootFacts = await readSessionFacts(ctx, rootId, signal)
323
+ if (rootFacts === null) throw new Error(`session "${rootId}" could not be read`)
324
+
325
+ const rows = await listFleetRows(ctx, rootId, signal)
326
+ const seen = new Set([rootId])
327
+ const children = []
328
+ let total = sumBuckets(rootFacts.buckets)
329
+ let complete = true
330
+ for (const row of rows) {
331
+ const id = rowIdOf(row)
332
+ if (id === null || seen.has(id)) continue
333
+ seen.add(id)
334
+ const title = rowTitleOf(row)
335
+ if (row?.kind === 'diagnostic' || row?.mode === 'external') {
336
+ complete = false
337
+ children.push(childRow(id, STATUS.unavailable, title))
338
+ continue
339
+ }
340
+ const facts = await readSessionFacts(ctx, id, signal)
341
+ if (facts === null) complete = false
342
+ else total += sumBuckets(facts.buckets)
343
+ children.push(childRow(id, statusOfFacts(facts, row?.mode), title))
344
+ }
345
+
346
+ const agentRunning = rootFacts.turnOpen === true
347
+ if (!complete) {
348
+ return {
349
+ ok: true,
350
+ sessionId: rootId,
351
+ tokensComplete: false,
352
+ totalTokens: null,
353
+ flowTokens: null,
354
+ agentRunning,
355
+ children,
356
+ }
357
+ }
358
+ const tokens = Math.max(0, total)
359
+ return {
360
+ ok: true,
361
+ sessionId: rootId,
362
+ tokensComplete: true,
363
+ totalTokens: tokens,
364
+ flowTokens: tokens,
365
+ agentRunning,
366
+ children,
367
+ }
368
+ }
369
+
370
+ export function debugPayload(ctx, selected) {
371
+ const { sessionCache, headerCache } = stateOf(ctx)
372
+ return {
373
+ selected: typeof selected === 'string' && selected !== '' ? selected : null,
374
+ services: {
375
+ sessions: Boolean(readService(ctx, 'sessions')),
376
+ sessionQuery: Boolean(readService(ctx, 'sessionQuery')),
377
+ subagents: Boolean(readService(ctx, 'subagents')),
378
+ agents: Boolean(readService(ctx, 'agents')),
379
+ },
380
+ cache: { sessions: sessionCache.size, headers: headerCache.size },
381
+ }
382
+ }
383
+
package/icon.svg ADDED
@@ -0,0 +1,19 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="Ocean background">
2
+ <defs>
3
+ <linearGradient id="sky" x1="0" y1="0" x2="0" y2="1">
4
+ <stop offset="0" stop-color="#bcdcea"/>
5
+ <stop offset="1" stop-color="#e7f2f4"/>
6
+ </linearGradient>
7
+ <linearGradient id="sea" x1="0" y1="0" x2="0" y2="1">
8
+ <stop offset="0" stop-color="#3f9ea6"/>
9
+ <stop offset="1" stop-color="#12596b"/>
10
+ </linearGradient>
11
+ </defs>
12
+ <rect width="64" height="64" rx="14" fill="url(#sky)"/>
13
+ <path d="M0 40c8 0 8-4 16-4s8 4 16 4 8-4 16-4 8 4 16 4v24H0z" fill="url(#sea)"/>
14
+ <path d="M31 12v26" stroke="#2c3e46" stroke-width="2.4" stroke-linecap="round"/>
15
+ <path d="M33 14 48 34H33z" fill="#f6f1e6" stroke="#d9cfbc" stroke-width="1"/>
16
+ <path d="M29 17 18 34h11z" fill="#efe8da" stroke="#d9cfbc" stroke-width="1"/>
17
+ <path d="M20 40h24l-4 7H24z" fill="#5b3722"/>
18
+ <path d="M0 52c8 0 8-3 16-3s8 3 16 3 8-3 16-3 8 3 16 3v12H0z" fill="#0c3d4a" opacity=".5"/>
19
+ </svg>