@thready-web/dsh-bot-plugin 0.1.0-beta.1 → 0.1.0-beta.3

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/dist/cli.js CHANGED
@@ -105,7 +105,7 @@ export async function run(argv, options = {}) {
105
105
  }
106
106
  else if (command === 'session' && action === 'bind') {
107
107
  const engine = openEngine();
108
- const binding = engine.bindPersona(required(flags, 'session'), flags.persona ? Number(flags.persona) : engine.latestPersona()?.id ?? null);
108
+ const binding = engine.bindPersona(required(flags, 'session'), flags.persona ? Number(flags.persona) : (engine.latestPersona()?.id ?? null));
109
109
  console.log(JSON.stringify({ ok: true, binding }, null, 2));
110
110
  engine.store.close();
111
111
  }
@@ -144,8 +144,12 @@ export async function run(argv, options = {}) {
144
144
  const sessionId = required(flags, 'session');
145
145
  engine.ensureSession(sessionId);
146
146
  console.log(JSON.stringify({
147
- facts: engine.store.db.prepare('SELECT id, status, revision, priority, content FROM facts WHERE session_id = ? ORDER BY id').all(sessionId),
148
- memories: engine.store.db.prepare('SELECT id, status, revision, title, content FROM memories WHERE session_id = ? ORDER BY id').all(sessionId),
147
+ facts: engine.store.db
148
+ .prepare('SELECT id, status, revision, priority, content FROM facts WHERE session_id = ? ORDER BY id')
149
+ .all(sessionId),
150
+ memories: engine.store.db
151
+ .prepare('SELECT id, status, revision, title, content FROM memories WHERE session_id = ? ORDER BY id')
152
+ .all(sessionId),
149
153
  state: engine.statePayload(sessionId),
150
154
  }, null, 2));
151
155
  engine.store.close();
@@ -167,7 +171,9 @@ export async function run(argv, options = {}) {
167
171
  }
168
172
  else if (command === 'skill' && action === 'list') {
169
173
  const engine = openEngine();
170
- const rows = engine.store.db.prepare('SELECT * FROM skill_bindings WHERE session_id = ? ORDER BY skill_id').all(required(flags, 'session'));
174
+ const rows = engine.store.db
175
+ .prepare('SELECT * FROM skill_bindings WHERE session_id = ? ORDER BY skill_id')
176
+ .all(required(flags, 'session'));
171
177
  console.log(JSON.stringify({ ok: true, skills: rows }, null, 2));
172
178
  engine.store.close();
173
179
  }
@@ -183,19 +189,30 @@ export async function run(argv, options = {}) {
183
189
  }
184
190
  else if (command === 'message' && action === 'list') {
185
191
  const triggers = openTriggers();
186
- console.log(JSON.stringify({ ok: true, acl: triggers.listAcl(), deliveries: triggers.listDeliveries(flags.session ?? '', flags.correlation ?? '') }, null, 2));
192
+ console.log(JSON.stringify({
193
+ ok: true,
194
+ acl: triggers.listAcl(),
195
+ deliveries: triggers.listDeliveries(flags.session ?? '', flags.correlation ?? ''),
196
+ }, null, 2));
187
197
  triggersClose();
188
198
  }
189
199
  else if (command === 'work' && action === 'dispatch') {
190
200
  const engine = openEngine();
191
201
  const sessionId = required(flags, 'session');
192
202
  if (!engine.isBot(sessionId)) {
193
- console.log(JSON.stringify({ ok: false, code: 'FORBIDDEN', message: 'An ordinary session stays on one loop and cannot dispatch work.' }, null, 2));
203
+ console.log(JSON.stringify({
204
+ ok: false,
205
+ code: 'FORBIDDEN',
206
+ message: 'An ordinary session stays on one loop and cannot dispatch work.',
207
+ }, null, 2));
194
208
  engine.store.close();
195
209
  process.exitCode = 1;
196
210
  }
197
211
  else {
198
- const work = createWorkRuntime(engine.store, engine, { resident: false, push: async () => ({ ok: false, ambiguous: true }) });
212
+ const work = createWorkRuntime(engine.store, engine, {
213
+ resident: false,
214
+ push: async () => ({ ok: false, ambiguous: true }),
215
+ });
199
216
  const result = await work.dispatch(sessionId, {
200
217
  briefing: required(flags, 'text'),
201
218
  idempotencyKey: flags.key,
@@ -215,16 +232,19 @@ export async function run(argv, options = {}) {
215
232
  });
216
233
  console.log(JSON.stringify({
217
234
  ...result,
218
- ...('status' in result && result.status === 'intent' ? {
219
- queued: false,
220
- note: 'Only the intent was written. A resident DSH host reconciles it and then followup reaches the native inbox. This process will not execute after it exits.',
221
- } : {}),
235
+ ...('status' in result && result.status === 'intent'
236
+ ? {
237
+ queued: false,
238
+ note: 'Only the intent was written. A resident DSH host reconciles it and then followup reaches the native inbox. This process will not execute after it exits.',
239
+ }
240
+ : {}),
222
241
  }, null, 2));
223
242
  triggersClose();
224
243
  if (!result.ok)
225
244
  process.exitCode = 1;
226
245
  }
227
- else if (command === 'timer' && (action === 'add' || action === 'list' || action === 'pause' || action === 'resume' || action === 'delete')) {
246
+ else if (command === 'timer' &&
247
+ (action === 'add' || action === 'list' || action === 'pause' || action === 'resume' || action === 'delete')) {
228
248
  const triggers = openTriggers();
229
249
  if (action === 'add') {
230
250
  const result = triggers.addSchedule({
package/dist/context.js CHANGED
@@ -98,14 +98,18 @@ export function renderSession(engine, sessionId, window = DEFAULT_WINDOW) {
98
98
  if (estimateTokens(stateText) > cap.state.soft)
99
99
  stateText = renderState(frozenState, true);
100
100
  const skills = Array.isArray(selected.skills) ? selected.skills : [];
101
- let skillText = skills.filter(skill => skill.enabled && !skill.revoked).map(skill => (`- ${skill.skill_id} ${skill.version} ${skill.scope} ${skill.summary ?? ''}`.trimEnd())).join('\n');
101
+ let skillText = skills
102
+ .filter((skill) => skill.enabled && !skill.revoked)
103
+ .map((skill) => `- ${skill.skill_id} ${skill.version} ${skill.scope} ${skill.summary ?? ''}`.trimEnd())
104
+ .join('\n');
102
105
  if (estimateTokens(skillText) > cap.skills.soft) {
103
- skillText = skills.filter(skill => skill.enabled && !skill.revoked).map(skill => (`- ${skill.skill_id} ${skill.version} enabled`)).join('\n');
106
+ skillText = skills
107
+ .filter((skill) => skill.enabled && !skill.revoked)
108
+ .map((skill) => `- ${skill.skill_id} ${skill.version} enabled`)
109
+ .join('\n');
104
110
  }
105
111
  const revoked = engine.revokedSkills(sessionId);
106
- const notice = revoked.length === 0
107
- ? ''
108
- : `Revoked. Later loads will refuse: ${revoked.map(skill => skill.skill_id).join(', ')}`;
112
+ const notice = revoked.length === 0 ? '' : `Revoked. Later loads will refuse: ${revoked.map(skill => skill.skill_id).join(', ')}`;
109
113
  const blocks = {
110
114
  chat: CHAT,
111
115
  soul: soulCode
@@ -130,13 +134,19 @@ export function renderSession(engine, sessionId, window = DEFAULT_WINDOW) {
130
134
  'foundations:soul': blocks.soul,
131
135
  'foundations:chat': CHAT,
132
136
  'foundations:rules': RULES,
133
- 'foundations:user': blocks.user ? `[foundations:user]\nThese are facts about the user. They are not your name, and they are not your persona.\n${blocks.user}` : '',
134
- 'foundations:facts': blocks.facts ? `[foundations:facts]\nThese are also facts about the user, not your name.\n${blocks.facts}` : '',
137
+ 'foundations:user': blocks.user
138
+ ? `[foundations:user]\nThese are facts about the user. They are not your name, and they are not your persona.\n${blocks.user}`
139
+ : '',
140
+ 'foundations:facts': blocks.facts
141
+ ? `[foundations:facts]\nThese are also facts about the user, not your name.\n${blocks.facts}`
142
+ : '',
135
143
  'foundations:state': blocks.state ? `[foundations:state]\n${blocks.state}` : '',
136
144
  'foundations:skills': blocks.skills ? `[foundations:skills]\n${blocks.skills}` : '',
137
145
  'foundations:revocation': blocks.notice ? `[foundations:revocation]\n${blocks.notice}` : '',
138
146
  };
139
- const snapshotHash = sha256(Object.entries(rendered).map(([name, text]) => `${name}\n${text}`).join('\n'));
147
+ const snapshotHash = sha256(Object.entries(rendered)
148
+ .map(([name, text]) => `${name}\n${text}`)
149
+ .join('\n'));
140
150
  const previous = view.snapshot_hash;
141
151
  let presence = view.presence;
142
152
  if (previous === 'pending')
@@ -181,7 +191,9 @@ export function frameSoul(soul) {
181
191
  const { name, body } = splitPersona(soul);
182
192
  if (name === '' && body === '')
183
193
  return '';
184
- const lines = ['The persona below is your identity. Enter this role in the first person and keep it for the whole conversation.'];
194
+ const lines = [
195
+ 'The persona below is your identity. Enter this role in the first person and keep it for the whole conversation.',
196
+ ];
185
197
  if (name !== '') {
186
198
  lines.push(`Your name is "${name}". This is your name, not the user's name, and not a nickname for the user.`);
187
199
  lines.push('When the user asks what you are called, who you are, or how to address you, answer with this name only. Do not say you have no name. Do not substitute DeepSeek, Harness, the host product name, or a model id.');
package/dist/cron.js CHANGED
@@ -33,7 +33,7 @@ export function nextCron(expr, afterMs, timeZone) {
33
33
  const weekMatch = spec.weekday.has(parts.weekday);
34
34
  const dayStar = spec.day.size === 31;
35
35
  const weekStar = spec.weekday.size === 7;
36
- const dayOk = dayStar && weekStar ? true : dayStar ? weekMatch : weekStar ? dayMatch : (dayMatch || weekMatch);
36
+ const dayOk = dayStar && weekStar ? true : dayStar ? weekMatch : weekStar ? dayMatch : dayMatch || weekMatch;
37
37
  if (dayOk)
38
38
  return new Date(cursor).toISOString();
39
39
  }
package/dist/desk.js CHANGED
@@ -1,9 +1,31 @@
1
1
  /** Workbench routes inside the DSH process. The browser calls /dsh-bot/api. */
2
- import { readFileSync } from 'node:fs';
3
- import { dirname, join } from 'node:path';
2
+ import { mkdirSync, readFileSync } from 'node:fs';
3
+ import { dirname, join, resolve } from 'node:path';
4
4
  import { openLedger, validIdempotencyKey } from "./desk-ledger.js";
5
5
  import { openSessionPreviews } from "./session-previews.js";
6
6
  import { purgeSessionFiles, sessionDirectory, writeBotMarker } from "./session-files.js";
7
+ /**
8
+ * Working directory for workbench-created sessions. THREADY_SESSION_CWD wins;
9
+ * otherwise <DSH_HOME>/workspace, so the model does not start inside DSH_HOME
10
+ * (owner-token, profiles/, persona.sqlite). Empty only when neither is set,
11
+ * which keeps DSH's own default (the server process cwd).
12
+ * @param {Record<string, string | undefined>} env
13
+ * @param {{ mkdir?: boolean }} [options]
14
+ */
15
+ export function defaultSessionCwd(env, options = {}) {
16
+ const explicit = (env.THREADY_SESSION_CWD ?? '').trim();
17
+ const home = (env.DSH_HOME ?? '').trim();
18
+ const cwd = explicit !== '' ? resolve(explicit) : home !== '' ? join(resolve(home), 'workspace') : '';
19
+ if (cwd !== '' && options.mkdir !== false) {
20
+ try {
21
+ mkdirSync(cwd, { recursive: true, mode: 0o700 });
22
+ }
23
+ catch {
24
+ /* session/create reports a bad cwd */
25
+ }
26
+ }
27
+ return cwd;
28
+ }
7
29
  const API = '/session-foundations/api';
8
30
  const PREVIEW_SESSION = /^(?:session|worker)-[A-Za-z0-9-]+$/;
9
31
  const SECRET_KEY = /token|secret|password|authorization|api[-_]?key|cookie/i;
@@ -16,8 +38,8 @@ const SECRET_KEY = /token|secret|password|authorization|api[-_]?key|cookie/i;
16
38
  * @param {(sessionId: string) => { kind?: string } | null | undefined} options.mark
17
39
  * @param {(sessionId: string) => void | Promise<void>} options.hold
18
40
  * @param {(sessionId: string) => void | Promise<void>} options.release
19
- * @param {(endpoint: string, args: Record<string, unknown>, req: import('node:http').IncomingMessage) => Promise<{ status: number, body: RpcEnvelope }>} options.rpc
20
- * @param {(req: import('node:http').IncomingMessage) => Promise<Record<string, unknown>>} options.usage
41
+ * @param {(endpoint: string, args: Record<string, unknown>, req: DeskRequest) => Promise<{ status: number, body: RpcEnvelope }>} options.rpc
42
+ * @param {(req: DeskRequest) => Promise<Record<string, unknown>>} options.usage
21
43
  */
22
44
  export function createDesk(options) {
23
45
  const ledger = openLedger(options.ledgerFile);
@@ -34,7 +56,8 @@ export function createDesk(options) {
34
56
  const sub = subpath(path);
35
57
  if (sub === null)
36
58
  return false;
37
- if (method === 'GET' && (sub === '/health' || sub === '/sessions' || sub === '/tasks' || sub === '/usage' || sub === '/file'))
59
+ if (method === 'GET' &&
60
+ (sub === '/health' || sub === '/sessions' || sub === '/tasks' || sub === '/usage' || sub === '/file'))
38
61
  return true;
39
62
  if (method === 'POST' && (sub === '/sessions' || sub === '/sessions/previews' || sub === '/tasks'))
40
63
  return true;
@@ -48,7 +71,7 @@ export function createDesk(options) {
48
71
  * @param {string} method
49
72
  * @param {string} path
50
73
  * @param {URL} url
51
- * @param {import('node:http').IncomingMessage} req
74
+ * @param {DeskRequest} req
52
75
  */
53
76
  async handle(method, path, url, req) {
54
77
  const sub = subpath(path) ?? '';
@@ -84,7 +107,7 @@ export function createDesk(options) {
84
107
  },
85
108
  };
86
109
  /**
87
- * @param {import('node:http').IncomingMessage} req
110
+ * @param {DeskRequest} req
88
111
  */
89
112
  async function health(req) {
90
113
  const execution = await executionState(req);
@@ -94,7 +117,7 @@ export function createDesk(options) {
94
117
  };
95
118
  }
96
119
  /**
97
- * @param {import('node:http').IncomingMessage} req
120
+ * @param {DeskRequest} req
98
121
  */
99
122
  async function executionState(req) {
100
123
  const catalog = await options.rpc('session/modelCatalog', {}, req);
@@ -105,12 +128,12 @@ export function createDesk(options) {
105
128
  const failure = catalog.body?.result?.error?.message;
106
129
  return {
107
130
  ready: false,
108
- reason: catalog.body?.result?.ok === true ? 'no_provider' : (failure ? String(failure) : 'catalog_unreadable'),
131
+ reason: catalog.body?.result?.ok === true ? 'no_provider' : failure ? String(failure) : 'catalog_unreadable',
109
132
  reachable: catalog.status > 0 && catalog.status < 500,
110
133
  };
111
134
  }
112
135
  /**
113
- * @param {import('node:http').IncomingMessage} req
136
+ * @param {DeskRequest} req
114
137
  * @param {Record<string, unknown>} body
115
138
  */
116
139
  async function createSession(req, body) {
@@ -126,7 +149,10 @@ export function createDesk(options) {
126
149
  : [];
127
150
  const reusable = options.sessionCwd === ''
128
151
  ? undefined
129
- : known.find(item => item?.blank === true && item?.running !== true && item?.cwd === options.sessionCwd && typeof item.sessionId === 'string');
152
+ : known.find((item) => item?.blank === true &&
153
+ item?.running !== true &&
154
+ item?.cwd === options.sessionCwd &&
155
+ typeof item.sessionId === 'string');
130
156
  const request = options.sessionCwd === ''
131
157
  ? {}
132
158
  : reusable
@@ -156,10 +182,13 @@ export function createDesk(options) {
156
182
  }
157
183
  }
158
184
  ledger.rememberSession(key, sessionId);
159
- return { status: 201, body: { sessionId, kind: 'bot', marker, reused: Boolean(reusable) && sessionId === reusable.sessionId } };
185
+ return {
186
+ status: 201,
187
+ body: { sessionId, kind: 'bot', marker, reused: Boolean(reusable) && sessionId === reusable.sessionId },
188
+ };
160
189
  }
161
190
  /**
162
- * @param {import('node:http').IncomingMessage} req
191
+ * @param {DeskRequest} req
163
192
  * @param {string} sessionId
164
193
  */
165
194
  async function archiveBlank(req, sessionId) {
@@ -181,7 +210,7 @@ export function createDesk(options) {
181
210
  return { status: 200, body: { sessionId, archivedSessionIds } };
182
211
  }
183
212
  /**
184
- * @param {import('node:http').IncomingMessage} req
213
+ * @param {DeskRequest} req
185
214
  * @param {string} sessionId
186
215
  */
187
216
  async function purgeBlank(req, sessionId) {
@@ -206,7 +235,10 @@ export function createDesk(options) {
206
235
  });
207
236
  }
208
237
  catch (error) {
209
- return { status: 500, body: { error: 'purge_failed', message: error instanceof Error ? error.message : 'purge failed' } };
238
+ return {
239
+ status: 500,
240
+ body: { error: 'purge_failed', message: error instanceof Error ? error.message : 'purge failed' },
241
+ };
210
242
  }
211
243
  sessionPreviews.forget(sessionId);
212
244
  return { status: 200, body: { sessionId, purged: true } };
@@ -233,7 +265,7 @@ export function createDesk(options) {
233
265
  return { status: 200, body: { ok: true, preview: saved.preview } };
234
266
  }
235
267
  /**
236
- * @param {import('node:http').IncomingMessage} req
268
+ * @param {DeskRequest} req
237
269
  * @param {Record<string, unknown>} body
238
270
  */
239
271
  async function createTask(req, body) {
@@ -254,7 +286,14 @@ export function createDesk(options) {
254
286
  if (!remembered.created)
255
287
  return { status: 200, body: { task: remembered.record, reused: true } };
256
288
  if (!execution.ready) {
257
- return { status: 409, body: { error: 'model_unconfigured', task: remembered.record, execution: { ready: false, reason: execution.reason } } };
289
+ return {
290
+ status: 409,
291
+ body: {
292
+ error: 'model_unconfigured',
293
+ task: remembered.record,
294
+ execution: { ready: false, reason: execution.reason },
295
+ },
296
+ };
258
297
  }
259
298
  const delivered = await withPromptLock(sessionId, () => deliverPrompt(req, sessionId, text, remembered.record.id));
260
299
  if (!delivered.ok) {
@@ -263,12 +302,16 @@ export function createDesk(options) {
263
302
  reason: delivered.reason,
264
303
  upstreamCode: delivered.upstreamCode,
265
304
  });
266
- return { status: delivered.status, body: { error: delivered.error, task: updated } };
305
+ const failStatus = delivered.status;
306
+ return {
307
+ status: typeof failStatus === 'number' ? failStatus : 502,
308
+ body: { error: delivered.error, task: updated },
309
+ };
267
310
  }
268
311
  return { status: 202, body: { task: remembered.record, reused: false, interrupted: delivered.interrupted } };
269
312
  }
270
313
  /**
271
- * @param {import('node:http').IncomingMessage} req
314
+ * @param {DeskRequest} req
272
315
  * @param {string} id
273
316
  */
274
317
  async function cancelTask(req, id) {
@@ -286,7 +329,7 @@ export function createDesk(options) {
286
329
  return { status: result.body?.result?.ok === true ? 200 : 502, body: { task: updated } };
287
330
  }
288
331
  /**
289
- * @param {import('node:http').IncomingMessage} req
332
+ * @param {DeskRequest} req
290
333
  * @param {URL} url
291
334
  */
292
335
  async function filePreview(req, url) {
@@ -357,7 +400,7 @@ export function createDesk(options) {
357
400
  }
358
401
  }
359
402
  /**
360
- * @param {import('node:http').IncomingMessage} req
403
+ * @param {DeskRequest} req
361
404
  * @param {string} sessionId
362
405
  * @returns {Promise<boolean | null>}
363
406
  */
@@ -365,13 +408,13 @@ export function createDesk(options) {
365
408
  const listed = await options.rpc('session/list', { _request: {} }, req);
366
409
  if (listed.body?.result?.ok !== true || !Array.isArray(listed.body.result.value?.items))
367
410
  return null;
368
- const item = listed.body.result.value.items.find(entry => entry?.sessionId === sessionId);
411
+ const item = listed.body.result.value.items.find((entry) => entry?.sessionId === sessionId);
369
412
  return item?.running === true;
370
413
  }
371
414
  /**
372
415
  * Idle sessions queue. A live bot turn is cancelled, then the new text is a new turn.
373
416
  * The cancel is only the main session. Worker sessions are not addressed here.
374
- * @param {import('node:http').IncomingMessage} req
417
+ * @param {DeskRequest} req
375
418
  * @param {string} sessionId
376
419
  * @param {string} text
377
420
  * @param {string} requestId
@@ -379,7 +422,13 @@ export function createDesk(options) {
379
422
  async function deliverPrompt(req, sessionId, text, requestId) {
380
423
  const running = await sessionRunning(req, sessionId);
381
424
  if (running === null) {
382
- return { ok: false, status: 502, error: 'session_unreadable', reason: 'Could not tell whether the session is still running.', upstreamCode: '' };
425
+ return {
426
+ ok: false,
427
+ status: 502,
428
+ error: 'session_unreadable',
429
+ reason: 'Could not tell whether the session is still running.',
430
+ upstreamCode: '',
431
+ };
383
432
  }
384
433
  let interrupted = false;
385
434
  if (running && (options.isBot(sessionId) || botMarked(sessionId))) {
@@ -430,7 +479,7 @@ function subpath(path) {
430
479
  return path.slice(API.length);
431
480
  }
432
481
  /**
433
- * @param {import('node:http').IncomingMessage} req
482
+ * @param {DeskRequest} req
434
483
  * @param {Record<string, unknown>} body
435
484
  */
436
485
  function idempotencyOf(req, body) {
@@ -480,7 +529,7 @@ function redactSecrets(value) {
480
529
  return value;
481
530
  }
482
531
  /**
483
- * @param {import('node:http').IncomingMessage} req
532
+ * @param {DeskRequest} req
484
533
  * @returns {Promise<Record<string, unknown>>}
485
534
  */
486
535
  function readJson(req) {