dsh-cindy-host 0.1.35 → 0.1.37

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,58 @@
1
+ import { createReasoningStream } from './reasoning-stream.js';
2
+
3
+ /** Internal source-order projection. Cut metadata/retired bodies stay local; raw rowid is an existing wire field. */
4
+ export function createHistoryProjection(sessionId) {
5
+ const reasoning = createReasoningStream(sessionId);
6
+ const stored = new Map();
7
+ const retired = new Map();
8
+ let ordinal = 0;
9
+ let liveBase = 0;
10
+ let scope = null;
11
+ let live = [];
12
+ const compare = (a, b) => a[0] - b[0] || a[1] - b[1];
13
+
14
+ function consume(event, rows = []) {
15
+ const position = ordinal++;
16
+ const before = live;
17
+ reasoning.consume(event);
18
+ const entries = reasoning.entries();
19
+ const nextScope = entries[0]?.scope ?? null;
20
+ if (entries.length && scope !== nextScope) liveBase = position;
21
+ scope = nextScope;
22
+ live = entries.map(({ row, index }) => ({ row, position: [liveBase, index] }));
23
+ const current = new Set(live.map(entry => entry.row.clientId));
24
+ for (const entry of before) {
25
+ if (!current.has(entry.row.clientId)) retired.set(entry.row.clientId, entry.position);
26
+ }
27
+ rows.forEach((row, index) => stored.set(row.id, { row, position: [position, index] }));
28
+ }
29
+
30
+ function snapshot({ rowids = false } = {}) {
31
+ const entries = [...stored.values(), ...live].sort((a, b) => compare(a.position, b.position));
32
+ const rows = entries.map(entry => {
33
+ if (!rowids) return entry.row;
34
+ const rowid = entry.position[0] * 65536 + entry.position[1];
35
+ if (!Number.isSafeInteger(rowid) || entry.position[1] >= 65536) throw Object.assign(new Error('Message order exceeds the safe protocol range'), { code: 'DELIVERY_EVIDENCE_CORRUPT' });
36
+ return { ...entry.row, rowid };
37
+ });
38
+ const ids = new Map();
39
+ rows.forEach((row, index) => {
40
+ ids.set(row.id, index);
41
+ if (row.role === 'thinking') {
42
+ ids.set(`history-live:${row.clientId}`, index);
43
+ // Pre-upgrade reasoning-stream IDs are the logical clientId itself.
44
+ ids.set(row.clientId, index);
45
+ }
46
+ });
47
+ const retiredCuts = new Map(retired);
48
+ return { rows, resolve(id, { cut = false } = {}) {
49
+ if (ids.has(id)) return ids.get(id);
50
+ const key = typeof id === 'string' && id.startsWith('history-live:') ? id.slice(13) : id;
51
+ const position = cut ? retiredCuts.get(key) : undefined;
52
+ if (!position) return -1;
53
+ const index = entries.findIndex(entry => compare(entry.position, position) >= 0);
54
+ return index < 0 ? rows.length : index;
55
+ } };
56
+ }
57
+ return { consume, snapshot, reasoning };
58
+ }
@@ -1,12 +1,11 @@
1
1
  /**
2
- * The history view's page budgets, mirrored from the Cindy contract.
2
+ * Conservative Host page budgets within the Cindy v1 contract.
3
3
  *
4
4
  * Stated here rather than imported because this Host composes the protocol over the wire,
5
- * not the package: `@cindy/maker-shared/message-window` publishes
6
- * `HISTORY_VIEW_PAGE_ITEMS = 20`, `HISTORY_VIEW_PAGE_BYTES = 256 * 1024`,
7
- * `HISTORY_DETAIL_PAGE_BYTES = 256 * 1024`, and `HISTORY_VIEW_VERSION = 1`. A change on
8
- * the Cindy side shows up as a failing test here instead of a page the phone silently
9
- * truncates.
5
+ * not the package. The current Cindy v1 view ceiling is 1 MiB, with 20 items and
6
+ * a 256 KiB detail page. This Host deliberately keeps its view budget at 256 KiB;
7
+ * a smaller service budget is compatible and avoids increasing mobile load. These
8
+ * values are Host budgets, not an assertion that all current upstream limits match.
10
9
  */
11
10
 
12
11
  /** Items one `local-db:messages:view` page may carry. */
@@ -29,8 +29,8 @@
29
29
  * - `intent` replaces the set of expanded work keys wholesale; it is advisory.
30
30
  * - An error whose text matches `isHistoryViewUnavailable` sends the controller back to
31
31
  * the raw window. `UNSUPPORTED_CAPABILITY` is therefore how this Host *deliberately*
32
- * declines a session it cannot project (a transcript past the scan budget) — the same
33
- * lever the reference uses.
32
+ * declines an unavailable projection capability, never a large or stale session.
33
+ * Per-session missing references use retryable NOT_FOUND/BAD_REQUEST instead.
34
34
  *
35
35
  * Grouping here is by **DSH turn boundary as the controller can see it**: a row whose role
36
36
  * is `user` starts a work group, and everything up to the next one belongs to it. The
@@ -129,8 +129,8 @@ function isActivityRow(row) {
129
129
  * default) derives it: a transcript that does not end in an answer is still being written.
130
130
  * @returns items in **chronological** order, oldest first.
131
131
  */
132
- export function groupHistoryItems(rows, { running = null, maxWorkRows = WORK_ITEM_MAX_ROWS } = {}) {
133
- const chronological = [...rows].reverse();
132
+ export function groupHistoryItems(rows, { running = null, maxWorkRows = WORK_ITEM_MAX_ROWS, chronological: inSourceOrder = false } = {}) {
133
+ const chronological = inSourceOrder ? rows : [...rows].reverse();
134
134
  const items = [];
135
135
  let run = [];
136
136
 
@@ -159,6 +159,7 @@ export function groupHistoryItems(rows, { running = null, maxWorkRows = WORK_ITE
159
159
 
160
160
  /** Rows of the live tail a streaming work item shows without being expanded. */
161
161
  export const WORK_PREVIEW_ROWS = 5;
162
+ export const WORK_PREVIEW_BYTES = 6 * 1024;
162
163
 
163
164
  /**
164
165
  * One work item for a run of activity rows.
@@ -190,8 +191,14 @@ function workItem(run, streaming) {
190
191
  // streaming group. Without it, folding activity into work items meant a long turn showed
191
192
  // nothing but a spinner: measured, the phone sat on 「一直在思考中转圈」 for minutes while
192
193
  // this Host pushed 100+ rows that were all inside a collapsed group.
193
- if (streaming && run.length > 0) {
194
- const tail = run.slice(Math.max(0, run.length - WORK_PREVIEW_ROWS));
194
+ const tail = [];
195
+ let previewBytes = 0;
196
+ if (streaming) for (let index = run.length - 1; index >= 0 && tail.length < WORK_PREVIEW_ROWS; index -= 1) {
197
+ const size = itemBytes(run[index]);
198
+ if (previewBytes + size > WORK_PREVIEW_BYTES) break;
199
+ tail.unshift(run[index]); previewBytes += size;
200
+ }
201
+ if (tail.length > 0) {
195
202
  const previewFirst = tail[0];
196
203
  const previewLast = tail[tail.length - 1];
197
204
  summary.preview = {
@@ -222,13 +229,15 @@ function itemBytes(item) {
222
229
  /**
223
230
  * Build the reader behind the three view channels.
224
231
  *
225
- * @param options - `rows` (the transcript reader's whole-transcript accessor),
232
+ * @param options - `snapshot` (explicit source-order rows and reference resolver),
233
+ * or `rows` for legacy callers with a strictly newest-first array,
226
234
  * `sessionRunning` (whether the session is in a turn right now, for `isStreaming`),
227
235
  * and the page/scan limits.
228
236
  * @returns `{ page, details, intent, expandedFor }`.
229
237
  */
230
238
  export function createHistoryViewController({
231
239
  rows,
240
+ snapshot,
232
241
  sessionRunning = () => false,
233
242
  pageItems = HISTORY_PAGE_ITEMS,
234
243
  pageBytes = HISTORY_PAGE_BYTES,
@@ -263,16 +272,20 @@ export function createHistoryViewController({
263
272
  if (typeof sessionId !== 'string' || sessionId === '') {
264
273
  return { ok: false, code: 'BAD_REQUEST', message: 'history view needs a session' };
265
274
  }
266
- if (typeof rows !== 'function') {
275
+ if (typeof rows !== 'function' && typeof snapshot !== 'function') {
267
276
  return { ok: false, code: 'NOT_AVAILABLE', message: 'this DSH Host cannot project session history' };
268
277
  }
269
278
  let all;
270
279
  try {
271
- all = await rows(sessionId);
280
+ all = typeof snapshot === 'function' ? await snapshot(sessionId) : await rows(sessionId);
272
281
  } catch {
273
282
  return { ok: false, code: 'NOT_FOUND', message: 'this session has no readable transcript' };
274
283
  }
275
- if (!Array.isArray(all)) return { ok: false, code: 'INTERNAL', message: 'the transcript could not be read' };
284
+ if (Array.isArray(all)) {
285
+ const chronological = [...all].reverse();
286
+ all = { rows: chronological, resolve: id => chronological.findIndex(row => row.id === id) };
287
+ }
288
+ if (!Array.isArray(all?.rows) || typeof all.resolve !== 'function') return { ok: false, code: 'INTERNAL', message: 'the transcript could not be read' };
276
289
  // Long transcripts are **served**, not refused.
277
290
  //
278
291
  // This was `all.length > scanMaxRows → UNSUPPORTED_CAPABILITY`, on the reasoning that the
@@ -293,7 +306,7 @@ export function createHistoryViewController({
293
306
  // `UNSUPPORTED_CAPABILITY` and `CHANNEL_NOT_ALLOWED` are therefore reserved for "this Host
294
307
  // has no projection capability at all" — a deployment fact — and never for a property of
295
308
  // one session. See ADR-0007's decision evolution.
296
- return { ok: true, rows: all };
309
+ return { ok: true, rows: all.rows, resolve: all.resolve };
297
310
  }
298
311
 
299
312
  /**
@@ -304,23 +317,17 @@ export function createHistoryViewController({
304
317
  async function page(sessionId, before = undefined) {
305
318
  const read = await transcriptFor(sessionId);
306
319
  if (read.ok !== true) return read;
307
- const items = groupHistoryItems(read.rows, {
308
- running: typeof sessionRunning === 'function' ? sessionRunning(sessionId) === true : null,
309
- });
310
-
311
- // `before` names a row inside the older part of the transcript: everything at or after
312
- // it has already been sent, so the next page starts strictly older than that item.
313
- let end = items.length;
320
+ let endRow = read.rows.length;
314
321
  if (typeof before === 'string' && before !== '') {
315
- const index = items.findIndex((item) => firstIdOf(item) === before
316
- || (item.type === 'work' && item.summary.lastMessageId === before));
317
- if (index >= 0) end = index;
318
- else {
319
- // A cursor this Host cannot place: answer the oldest page we have rather than the
320
- // newest one again, which is what re-serving the same rows would amount to.
321
- end = Math.min(items.length, pageItems);
322
- }
322
+ endRow = read.resolve(before, { cut: true });
323
+ if (endRow < 0) return { ok: false, code: 'NOT_FOUND', message: 'history cursor is no longer in this session' };
323
324
  }
325
+ // Cut by source position before grouping: an anchor may now lie inside a merged work.
326
+ const items = groupHistoryItems(read.rows.slice(0, endRow), {
327
+ chronological: true,
328
+ running: !before && (typeof sessionRunning === 'function' ? sessionRunning(sessionId) === true : null),
329
+ });
330
+ const end = items.length;
324
331
  const selected = [];
325
332
  let bytes = 1024;
326
333
  for (let index = end - 1; index >= 0; index -= 1) {
@@ -354,16 +361,16 @@ export function createHistoryViewController({
354
361
  const firstId = typeof ref?.firstMessageId === 'string' ? ref.firstMessageId : '';
355
362
  const lastId = typeof ref?.lastMessageId === 'string' ? ref.lastMessageId : '';
356
363
  if (firstId === '' || lastId === '') return { ok: false, code: 'BAD_REQUEST', message: 'a work range needs both endpoints' };
357
- // The transcript is newest first; the range is inclusive in log order.
358
- const chronological = [...read.rows].reverse();
359
- const from = chronological.findIndex((row) => row.id === firstId);
360
- const to = chronological.findIndex((row) => row.id === lastId);
364
+ // Both endpoints and the forward cursor resolve against one source-order snapshot.
365
+ const chronological = read.rows;
366
+ const from = read.resolve(firstId);
367
+ const to = read.resolve(lastId);
361
368
  if (from < 0 || to < 0 || to < from) return { ok: false, code: 'NOT_FOUND', message: 'this work range is no longer in the transcript' };
362
369
  const range = chronological.slice(from, to + 1);
363
370
  let start = 0;
364
371
  if (typeof after === 'string' && after !== '') {
365
- const index = range.findIndex((row) => row.id === after);
366
- if (index < 0) return { ok: false, code: 'BAD_REQUEST', message: 'the detail cursor is outside this work range' };
372
+ const index = read.resolve(after) - from;
373
+ if (index < 0 || index >= range.length) return { ok: false, code: 'BAD_REQUEST', message: 'the detail cursor is outside this work range' };
367
374
  start = index + 1;
368
375
  }
369
376
  const messages = [];
@@ -35,7 +35,7 @@ export function createInputDeliveryCoordinator({store,backend,baseProjection=()=
35
35
  if((e.phase==='stored'||e.phase==='DSH-pending')&&e.queued){const at=pending.findIndex(p=>p.clientId===e.clientId);if(at<0)pending.push(e.queued);else pending[at]=e.queued;}
36
36
  }
37
37
  const running=runningBySession.get(sid)??base.turnInProgress;
38
- return {...base,...(typeof running==='boolean'?{turnInProgress:running}:{}),sessionId:sid,pendingQueue:pending,steeringQueueClientIds:[...steering],inputDeliveryVersion:1,clearBoundaryMs:store.boundary(sid),deliveryReceipts:ids.map(clientId=>{const e=store.get(sid,clientId);return{clientId,state:e?e.phase==='removed'?'removed':e.phase==='accepted'?'accepted':e.payload===undefined?'unknown':'pending':'unknown'};})};
38
+ return {...base,...(typeof running==='boolean'?{turnInProgress:running}:{}),sessionId:sid,pendingQueue:pending,steeringQueueClientIds:[...steering],inputDeliveryVersion:1,clearBoundaryMs:store.boundary(sid),deliveryReceipts:ids.map(clientId=>{const e=store.get(sid,clientId);return{clientId,state:e?e.phase==='removed'?'removed':e.phase==='accepted'?'accepted':e.payload===undefined?'unknown':'pending':'unknown',...(e?.removalReason?{reason:e.removalReason}:{})};})};
39
39
  }
40
40
  async function evidence(sid){
41
41
  const proof=await backend.evidence(sid);
@@ -85,7 +85,16 @@ export function createInputDeliveryCoordinator({store,backend,baseProjection=()=
85
85
  proof=await evidence(sid);
86
86
  const settled=store.get(sid,current.clientId);
87
87
  if(!terminal(settled.phase))save({...settled,phase:proof.inbox.some(item=>item.clientId===current.clientId)?'DSH-pending':'claimed',error:null});
88
- }catch(error){const e=store.get(sid,current.clientId);if(!terminal(e.phase))save({...e,...(error.deliveryNotAdmitted?{phase:'stored',...(error.deliveryRetryMode?{payload:{...e.payload,mode:error.deliveryRetryMode}}:{}),nextAttemptAt:now()+Math.min(30000,1000*2**Math.min(e.attemptNo??1,5))}:{}),error:String(error?.code??'DELIVERY_ADMISSION_UNCERTAIN')});onError(error);if(error.deliveryNotAdmitted){notify(sid);break;}}
88
+ }catch(error){const e=store.get(sid,current.clientId);
89
+ if(error.deliverySuperseded||(error.deliveryNotAdmitted&&error.code==='PLAN_MODE_UNAVAILABLE')){
90
+ const checked=await evidence(sid);const latest=store.get(sid,current.clientId);
91
+ if(latest.phase==='accepted')continue;
92
+ // Fresh native ownership wins over this attempt's early refusal. Never
93
+ // roll DSH-pending back to stored and accidentally permit re-admission.
94
+ if(checked.inbox.some(item=>item.clientId===current.clientId)){notify(sid);onError(error);break;}
95
+ save({...latest,phase:'removed',payload:null,error:error.code,removalReason:error.deliverySuperseded?'continuation-superseded':'continuation-plan-mode-unavailable'});notify(sid);continue;
96
+ }
97
+ if(!terminal(e.phase))save({...e,...(error.deliveryNotAdmitted?{phase:'stored',...(error.deliveryRetryMode?{payload:{...e.payload,mode:error.deliveryRetryMode}}:{}),nextAttemptAt:now()+Math.min(30000,1000*2**Math.min(e.attemptNo??1,5))}:{}),error:String(error?.code??'DELIVERY_ADMISSION_UNCERTAIN')});onError(error);if(error.deliveryNotAdmitted){notify(sid);break;}}
89
98
  notify(sid);
90
99
  }
91
100
  }
@@ -115,14 +124,24 @@ export function createInputDeliveryCoordinator({store,backend,baseProjection=()=
115
124
  if(row.durableDelivery===true && !hasBoundary)throw deliveryError('INVALID_PARAMS','Durable input requires expectedClearBoundaryMs, including explicit null');
116
125
  const expectedBoundary=hasBoundary?options.expectedClearBoundaryMs:store.boundary(sid);
117
126
  if(!e && expectedBoundary!==store.boundary(sid))throw deliveryError('REMOTE_OPTIMISTIC_INPUT_CLEARED','REMOTE_OPTIMISTIC_INPUT_CLEARED: input clear boundary changed');
118
- const prepared=await backend.prepare(sid,row,options);
127
+ const refuseContinuation = reason => {
128
+ const existing=store.get(sid,row.clientId);
129
+ if(existing?.phase==='removed')return view(sid,[row.clientId]);
130
+ if(existing)throw deliveryError('INPUT_DELIVERY_CONFLICT','clientId already belongs to an existing input');
131
+ save({sessionId:sid,clientId:row.clientId,phase:'removed',request:requestShape(row),rawFingerprint:raw,payload:null,queued:null,clearBoundaryMs:store.boundary(sid),createdAt:now(),attemptNo:0,cancelRequested:true,removalReason:reason});
132
+ notify(sid);return view(sid,[row.clientId]);
133
+ };
134
+ let prepared;
135
+ try{prepared=await backend.prepare(sid,row,options);}catch(error){if(error.code==='CONTINUATION_SUPERSEDED')return refuseContinuation('continuation-superseded');throw error;}
119
136
  if(!prepared || prepared.payload===undefined || !prepared.queued)throw deliveryError('DELIVERY_PREPARATION_FAILED','Host did not obtain complete replayable input');
120
137
  const {consumed: _transit,mode: _mode,...semanticPayload}=prepared.payload;const fingerprint=inputFingerprint(semanticPayload);e=store.get(sid,row.clientId);
121
138
  if(e){if(e.phase==='removed')return view(sid,[row.clientId]);if(e.fingerprint!==fingerprint)throw deliveryError('INPUT_DELIVERY_CONFLICT','clientId already belongs to a different input');return view(sid,[row.clientId]);}
122
139
  if(expectedBoundary!==store.boundary(sid))throw deliveryError('REMOTE_OPTIMISTIC_INPUT_CLEARED','REMOTE_OPTIMISTIC_INPUT_CLEARED: input was cleared during preparation');
140
+ const origin=prepared.payload.continuation;
141
+ if(origin&&store.list(sid).some(other=>other.clientId!==row.clientId&&other.phase!=='removed'&&other.continuation?.tailId===origin.tailId))return refuseContinuation('continuation-already-submitted');
123
142
  const preview=view(sid,[row.clientId]);preview.pendingQueue=[...preview.pendingQueue,prepared.queued];preview.deliveryReceipts=[{clientId:row.clientId,state:'pending'}];
124
143
  if(!validateProjection(preview))throw deliveryError('DELIVERY_TOO_LARGE','Input queue projection cannot fit the negotiated transport budget');
125
- save({sessionId:sid,clientId:row.clientId,phase:'stored',request:requestShape(row),rawFingerprint:raw,fingerprint,payload:prepared.payload,queued:prepared.queued,clearBoundaryMs:store.boundary(sid),sendAtMs:options.sendAtMs??null,createdAt:now(),attemptNo:0,cancelRequested:false});
144
+ save({sessionId:sid,clientId:row.clientId,phase:'stored',request:requestShape(row),rawFingerprint:raw,fingerprint,payload:prepared.payload,...(origin?{continuation:origin}:{}),queued:prepared.queued,clearBoundaryMs:store.boundary(sid),sendAtMs:options.sendAtMs??null,createdAt:now(),attemptNo:0,cancelRequested:false});
126
145
  notify(sid);schedule(sid);return view(sid,[row.clientId]);
127
146
  });
128
147
  },
@@ -5,7 +5,7 @@ export const SETTINGS_NAMESPACE = 'dsh-cindy-host';
5
5
  // Controller-only delete/pin metadata and legacy archive flags survive restart.
6
6
  // New archive/unarchive operations persist in DSH's native workspace registry;
7
7
  // legacy archived flags are retained until explicitly retired (see `session-flags.js`).
8
- export const DEFAULT_HOST_SETTINGS = Object.freeze({ transportEnabled: false, remoteControlEnabled: false, controllers: {}, deviceId: '', deviceName: '', sessionFlags: {} });
8
+ export const DEFAULT_HOST_SETTINGS = Object.freeze({ transportEnabled: false, remoteControlEnabled: false, controllers: {}, deviceId: '', deviceName: '', sessionFlags: {}, diagnosticPresentationV1: {} });
9
9
 
10
10
  /**
11
11
  * The Host's own relay identity, when it has one.
@@ -46,6 +46,20 @@ export function validateHostSettings(value) {
46
46
  }
47
47
  // An absent section is valid — every settings file written before this field
48
48
  // existed has none, and rejecting it would fail the load instead of the flag.
49
+ if (value.diagnosticPresentationV1 !== undefined) {
50
+ const record = entry => entry !== null && typeof entry === 'object' && !Array.isArray(entry);
51
+ const data=value.diagnosticPresentationV1;
52
+ if(!record(data))throw new Error('Invalid diagnostic presentation preferences');
53
+ for(const sessions of Object.values(data)){
54
+ if(!record(sessions))throw new Error('Invalid diagnostic owner preferences');
55
+ for(const kinds of Object.values(sessions)){
56
+ if(!record(kinds))throw new Error('Invalid diagnostic session preferences');
57
+ for(const [kind,ids] of Object.entries(kinds)){
58
+ if(!['errors','interruptions'].includes(kind)||!record(ids)||Object.values(ids).some(flag=>typeof flag!=='boolean'))throw new Error('Invalid diagnostic dismissal preferences');
59
+ }
60
+ }
61
+ }
62
+ }
49
63
  if (value.sessionFlags !== undefined) {
50
64
  if (value.sessionFlags === null || typeof value.sessionFlags !== 'object') throw new Error('Invalid session flags');
51
65
  for (const [sessionId, flags] of Object.entries(value.sessionFlags)) {
@@ -4,4 +4,4 @@
4
4
  */
5
5
  export const HOST_APP_VERSION = '0.1.82';
6
6
  /** Actual npm release, separate from the Cindy compatibility identity. */
7
- export const HOST_PLUGIN_VERSION = '0.1.35';
7
+ export const HOST_PLUGIN_VERSION = '0.1.37';