@goodandready/dsh-cron 0.3.30 → 0.3.31

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/README.md CHANGED
@@ -206,7 +206,7 @@ Every task picks its own runtime; non-LLM runtimes need no model and consume no
206
206
  * **SSH** (`ssh`) — execute a command on a remote host through a `dsh-remote-workspace` profile (`sshProfileId`) or standalone host/key fields.
207
207
  * **Docker** (`docker`) — run the command in a container image (`dockerImage`).
208
208
  * **Environment variables** — a per-task `env` map (KEY VALUE per line in the UI) applied to external runtimes; secrets do not belong here.
209
- * **Workspaces and worktrees** — bind a task to a harness workspace (`workspaceId`, resolved through host `workspaceRegistry`) or path, and run code-modifying agent tasks in an isolated git worktree (`worktree`, `keepWorktree`).
209
+ * **Workspaces and worktrees** — bind a task to a harness workspace (`workspaceId`, resolved through host `workspaceRegistry`) or path; the agent session created for the run is registered with that workspace's ledger (`attachSession`), so it appears under the project instead of ungrouped. Code-modifying agent tasks can run in an isolated git worktree (`worktree`, `keepWorktree`).
210
210
 
211
211
  ### 7. Cost Control: Fallback Model & Burn Guard
212
212
  * **Fallback Model** — A task can run on the cheap model by default and still finish on the strong one: set `fallbackModel` (and optionally `fallbackProvider`) and a failed run — `error` or `timeout` — is retried **once** on that model before the ordinary retry backoff applies. History records which model produced the result and whether the fallback was used, usage and cost of both attempts are summed, and the `{model}` template variable renders the model that finished the run. Only agent-mediated tasks (`llm`, `skill`, `workflow`) can use a fallback.
@@ -217,7 +217,7 @@ Every task picks its own runtime; non-LLM runtimes need no model and consume no
217
217
  ### 8. Session Integration & Permissions
218
218
  * **Real Assistant Output & Terminal Status Extraction** — Isolates current turn session events, extracts the actual assistant message text (excluding previous turn history in persistent sessions), and validates terminal turn status (`turn/end` errors or interruptions) to guarantee accurate reporting, chaining, and structured action execution.
219
219
  * **Per-task permission presets & unattended approval** — `default`, `read-only`, `workspace-write`, or `danger-full-access` (aliased as `full`) are mapped directly to host `SandboxMode` and applied to the task's agent session before the prompt runs. For unattended background runs, approval policy is pinned to `never` via host `approval` service to eliminate interactive approval stalls.
220
- * **Session auto-archive** — isolated cron sessions are archived after each run (best-effort) so they do not clutter the chat list.
220
+ * **Session auto-archive** — isolated cron sessions are archived after each run (best-effort, via host `workspaceRegistry.archiveSession`) so they do not clutter the chat list.
221
221
  * **History → session navigation** — every LLM run records its session; open it straight from the run history entry.
222
222
 
223
223
  ### 9. Quiet by Rule
@@ -433,7 +433,7 @@ Developer-facing, no behaviour change. `parseScheduleExpression` was split into
433
433
  - `daily`: Automatically rotates the session daily (`<id>-YYYY-MM-DD`).
434
434
  - `weekly`: Automatically rotates the session weekly (`<id>-YYYY-Www`).
435
435
  - Custom templating: Any `targetSessionId` containing `{{date}}` automatically interpolates today's date (`YYYY-MM-DD`).
436
- - **Main Chat Visibility**: Persistent sessions are omitted from `sessions.archive()` and unflagged from `ephemeral`/`internal`, making them visible and interactable directly in the DeepSeek Harness chat interface.
436
+ - **Main Chat Visibility**: Persistent sessions are omitted from `workspaceRegistry.archiveSession()` and unflagged from `ephemeral`/`internal`, making them visible and interactable directly in the DeepSeek Harness chat interface.
437
437
  - **Preset & Tooling Compatibility**: Resumed sessions automatically preserve and remount configured `agentPresets`, ensuring full access to workspace, terminal, and file tools on every turn.
438
438
  - *Inspiration credit*: Community idea originally explored by [@RaulLazaro](https://github.com/RaulLazaro).
439
439
 
package/README.ru.md CHANGED
@@ -205,7 +205,7 @@ cron({
205
205
  * **SSH** (`ssh`) — выполнение команды на удалённом хосте через профиль `dsh-remote-workspace` (`sshProfileId`) или отдельные поля host/key.
206
206
  * **Docker** (`docker`) — выполнение команды в контейнере образа (`dockerImage`).
207
207
  * **Переменные окружения** — карта `env` на задачу (в UI — строки KEY VALUE) для внешних рантаймов; секретам здесь не место.
208
- * **Workspace и worktree** — привязка задачи к workspace харнесса (`workspaceId`, разрешаемому через службу `workspaceRegistry`) или пути, и запуск в изолированном git worktree (`worktree`, `keepWorktree`).
208
+ * **Workspace и worktree** — привязка задачи к workspace харнесса (`workspaceId`, разрешаемому через службу `workspaceRegistry`) или пути; созданная для прогона сессия агента регистрируется в ведомости этого workspace (`attachSession`), поэтому появляется в группе проекта вместо «неразмещённых». Запуск в изолированном git worktree (`worktree`, `keepWorktree`).
209
209
 
210
210
  ### 7. Экономия: fallback-модель и защита бюджета (Burn Guard)
211
211
  * **Fallback-модель** — задача может идти на дешёвой модели по умолчанию и всё же завершиться на сильной: задайте `fallbackModel` (и при необходимости `fallbackProvider`), и сбойный запуск (`error` или `timeout`) один раз повторится на этой модели, прежде чем включится обычный retry с задержкой. В истории видно, какая модель произвела результат и был ли использован fallback; расход и стоимость обеих попыток суммируются; переменная шаблона `{model}` подставляет модель, завершившую запуск. Fallback доступен только агентским типам (`llm`, `skill`, `workflow`).
@@ -299,7 +299,7 @@ cron({
299
299
  - `daily`: ежедневная автоматическая ротация (`<id>-YYYY-MM-DD`).
300
300
  - `weekly`: еженедельная автоматическая ротация (`<id>-YYYY-Www`).
301
301
  - Шаблоны дат: в `targetSessionId` поддерживается плейсхолдер `{{date}}`, который автоматически заменяется на текущую дату `YYYY-MM-DD`.
302
- - **Видимость в списке чатов DSH**: Долговременные сессии не помечаются как `ephemeral`/`internal` и исключены из автоматической архивации (`sessions.archive()`), поэтому они остаются доступны для чтения и прямого диалога в веб-интерфейсе DSH.
302
+ - **Видимость в списке чатов DSH**: Долговременные сессии не помечаются как `ephemeral`/`internal` и исключены из автоматической архивации (`workspaceRegistry.archiveSession()`), поэтому они остаются доступны для чтения и прямого диалога в веб-интерфейсе DSH.
303
303
  - **Совместимость с пресетами и инструментами**: При возобновлении сессии автоматически подключаются инструменты пресета `agentPreset`, гарантируя доступ к терминалу, файлам и командам.
304
304
  - *Благодарность*: концепция вдохновлена разработкой [@RaulLazaro](https://github.com/RaulLazaro).
305
305
 
package/README.zh.md CHANGED
@@ -205,7 +205,7 @@ cron({
205
205
  * **SSH**(`ssh`)—— 通过 `dsh-remote-workspace` 配置(`sshProfileId`)或独立 host/key 字段在远程主机执行命令。
206
206
  * **Docker**(`docker`)—— 在镜像容器(`dockerImage`)中执行命令。
207
207
  * **环境变量** —— 按任务的 `env` 映射(界面中每行 KEY VALUE)应用于外部运行时;请勿在此存放密钥。
208
- * **工作区与 worktree** —— 将任务绑定到 Harness 工作区(`workspaceId`,通过宿主 `workspaceRegistry` 服务解析)或直接路径;对会修改代码的智能体任务,可在隔离的 git worktree 中运行(`worktree`、`keepWorktree`)。
208
+ * **工作区与 worktree** —— 将任务绑定到 Harness 工作区(`workspaceId`,通过宿主 `workspaceRegistry` 服务解析)或直接路径;运行创建的智能体会话会登记进该工作区的账本(`attachSession`),因此出现在项目分组下而非「未分组」。对会修改代码的智能体任务,可在隔离的 git worktree 中运行(`worktree`、`keepWorktree`)。
209
209
 
210
210
  ### 7. 成本控制:回退模型与支出保护(Burn Guard)
211
211
  * **回退模型** —— 任务可以默认使用便宜模型,失败时改用更强模型完成:设置 `fallbackModel`(可选 `fallbackProvider`),失败(`error` 或 `timeout`)的运行会在该模型上重试一次,之后才进入常规重试退避。历史记录会标明最终产出结果的模型以及是否使用了回退,两次尝试的用量与成本都会累计,模板变量 `{model}` 渲染完成运行的模型。回退仅适用于智能体类型(`llm`、`skill`、`workflow`)。
@@ -216,7 +216,7 @@ cron({
216
216
  ### 8. 会话集成与权限
217
217
  * **真实智能体输出与终端状态捕获** —— 隔离当前轮次的会话事件,提取最终真实的智能体回复文本(持久会话中自动排除以往历史轮次),并严格校验轮次终止状态(带有错误或中断的 `turn/end`),确保任务失败能准确反映到执行历史、链路调用及结构化指令中。
218
218
  * **按任务的权限预设** —— `default`、`read-only`、`workspace-write` 或 `full` 在提示词执行前应用于任务会话。
219
- * **会话自动归档** —— 隔离的 cron 会话在运行后自动归档(尽力而为),不干扰聊天列表。
219
+ * **会话自动归档** —— 隔离的 cron 会话在运行后自动归档(尽力而为,通过宿主 `workspaceRegistry.archiveSession`),不干扰聊天列表。
220
220
  * **历史 → 会话** —— 每次 LLM 运行都会记录会话,可直接从历史记录打开对话。
221
221
 
222
222
  ### 9. 按规则保持安静
@@ -424,7 +424,7 @@ bash deploy.sh verify [exact-version]
424
424
  - `daily`:每日自动开启全新子会话(后缀 `<id>-YYYY-MM-DD`)。
425
425
  - `weekly`:每周自动开启全新子会话(后缀 `<id>-YYYY-Www`)。
426
426
  - 日期变量插值:`targetSessionId` 中支持 `{{date}}` 占位符,自动注入当前日期 `YYYY-MM-DD`。
427
- - **主界面原生可见交互**:持久会话不会被标记为 `ephemeral`/`internal`,且在执行后跳过自动归档(`sessions.archive()`),用户可在 DSH 聊天列表中直接查看并继续手动对话。
427
+ - **主界面原生可见交互**:持久会话不会被标记为 `ephemeral`/`internal`,且在执行后跳过自动归档(`workspaceRegistry.archiveSession()`),用户可在 DSH 聊天列表中直接查看并继续手动对话。
428
428
  - **预设工具链无缝适配**:恢复会话时同样完整挂载 `agentPresets`,保障文件读写、代码编辑与终端工具持续可用。
429
429
  - *致谢*:功能灵感源自社区开发者 [@RaulLazaro](https://github.com/RaulLazaro)。
430
430
 
@@ -113,6 +113,49 @@ export class SessionRunner {
113
113
  }
114
114
  }
115
115
 
116
+ _getWorkspaceRegistry() {
117
+ if (!this.ctx) return null;
118
+ try {
119
+ if (typeof this.ctx.get === 'function') {
120
+ const svc = this.ctx.get('workspaceRegistry');
121
+ if (svc) return svc;
122
+ }
123
+ } catch (_err) {
124
+ // service unavailable via ctx.get
125
+ }
126
+ try {
127
+ return this.ctx.workspaceRegistry || null;
128
+ } catch (_err) {
129
+ return null;
130
+ }
131
+ }
132
+
133
+ /**
134
+ * Resolve the registered Workspace object for a task's workspaceId (workspace attach & archive).
135
+ * Mirrors the id/title/path lookup used by resolveCwd; returns null when the
136
+ * id is absent, the registry is unavailable, or no workspace matches.
137
+ */
138
+ _resolveWorkspace(task) {
139
+ const rawId = task?.workspaceId ? String(task.workspaceId).trim() : '';
140
+ if (!rawId) return null;
141
+ return bestEffort('resolve-workspace', () => {
142
+ const registry = this._getWorkspaceRegistry();
143
+ if (!registry) return null;
144
+ if (typeof registry.get === 'function') {
145
+ const ws = registry.get(rawId);
146
+ if (ws && typeof ws.attachSession === 'function') return ws;
147
+ }
148
+ if (typeof registry.list === 'function') {
149
+ const list = registry.list();
150
+ if (Array.isArray(list)) {
151
+ const matched = list.find((w) => w && (w.id === rawId || w.path === rawId || w.title === rawId));
152
+ if (matched && typeof matched.attachSession === 'function') return matched;
153
+ }
154
+ }
155
+ return null;
156
+ }) || null;
157
+ }
158
+
116
159
  async execute(task, options = {}) {
117
160
  const timeoutSeconds = Number(task.timeoutSeconds) > 0 ? Number(task.timeoutSeconds) : 1800;
118
161
  const timeoutMs = timeoutSeconds * 1000;
@@ -369,7 +412,16 @@ export class SessionRunner {
369
412
  // Context window overflow auto-recovery in persistent sessions (#145)
370
413
  if (prep.targetSessionId && isContextOverflowError(err) && !signal?.aborted) {
371
414
  logger.warn(`[dsh-cron] Persistent session "${prep.targetSessionId}" exceeded context window (${err.message}). Auto-recovering with fresh session...`);
372
- bestEffort('archive-rotated-session', () => {
415
+ // workspace attach & archive: the host SessionStore has no archive() method — the durable
416
+ // archive set lives on the workspaceRegistry. Archive the exhausted
417
+ // session there (the dispose in _executeAgentTurn's finally has already
418
+ // run, so the session is inactive).
419
+ await bestEffort('archive-rotated-session', async () => {
420
+ const registry = this._getWorkspaceRegistry();
421
+ if (registry && typeof registry.archiveSession === 'function') {
422
+ await registry.archiveSession(prep.targetSessionId);
423
+ return;
424
+ }
373
425
  const sessions = this.ctx?.get?.('sessions');
374
426
  if (sessions && typeof sessions.archive === 'function') {
375
427
  sessions.archive(prep.targetSessionId);
@@ -566,6 +618,17 @@ export class SessionRunner {
566
618
  }
567
619
  }
568
620
 
621
+ // workspace attach & archive: register the new session with its workspace ledger so it shows
622
+ // up under the project instead of "ungrouped". attachSession validates
623
+ // that the session cwd resolves to the workspace path, so skip when the
624
+ // run uses an isolated worktree (different cwd) or the workspaceId does
625
+ // not resolve to a registered workspace.
626
+ if (!isResumed && !prep.taskWorktree && task.workspaceId && handle?.agent?.session?.id) {
627
+ await bestEffort('attach-session-to-workspace', () =>
628
+ this._resolveWorkspace(task)?.attachSession(handle.agent.session.id)
629
+ );
630
+ }
631
+
569
632
  this._applyPermissionPreset(task, handle);
570
633
  this._nameSession(task, handle, isResumed);
571
634
  await prep.raceAbort(handle.agent.whenIdle());
@@ -864,9 +927,17 @@ export class SessionRunner {
864
927
  }
865
928
  // Best-effort: keep ephemeral cron sessions out of the main chat list (#30).
866
929
  // Persistent sessions (targetSessionId configured) stay unarchived so users can interact with them (#143).
867
- if (archivedSessionId && this.ctx && this.ctx.get && !prep.targetSessionId) {
868
- bestEffort('archive-session-cleanup', () => {
869
- const sessions = this.ctx.get('sessions');
930
+ if (archivedSessionId && this.ctx && !prep.targetSessionId) {
931
+ // workspace attach & archive: the host SessionStore has no archive() method (it was a silent
932
+ // no-op on every run). The durable archive set is written by
933
+ // workspaceRegistry.archiveSession, which needs no workspace membership.
934
+ await bestEffort('archive-session-cleanup', async () => {
935
+ const registry = this._getWorkspaceRegistry();
936
+ if (registry && typeof registry.archiveSession === 'function') {
937
+ await registry.archiveSession(archivedSessionId);
938
+ return;
939
+ }
940
+ const sessions = typeof this.ctx.get === 'function' ? this.ctx.get('sessions') : null;
870
941
  if (sessions && typeof sessions.archive === 'function') {
871
942
  sessions.archive(archivedSessionId);
872
943
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@goodandready/dsh-cron",
3
- "version": "0.3.30",
3
+ "version": "0.3.31",
4
4
  "description": "Background automation runner for DSH: isolated agent runs, script/HTTP/SSH/Docker runtimes, cost guard, notifications, heartbeats.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",