dsh-agent-lines 0.3.4 → 0.3.6

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/CHANGELOG.en.md CHANGED
@@ -2,6 +2,20 @@
2
2
 
3
3
  English | [中文](CHANGELOG.md)
4
4
 
5
+ ## 0.3.6 (2026-11-09)
6
+
7
+ - Added line lifecycle: line_retire, line_rebind, line_create replace:true, line_rename.
8
+ - Schema v7: lines.title/lifecycle/generation/rebind_at/rebind_from + line_events audit; additive migration from v6.
9
+ - Backlog migration: queued/claimed migrate; delivered/acked are never re-delivered; migrate:none fails closed when backlog is non-empty.
10
+ - Persistent titles: line_create/line_rename write lines.title and survive restarts.
11
+ - Tests 32/32 pass; existing 0.3.5 behavior unchanged.
12
+
13
+ ## 0.3.5 (2026-11-05)
14
+
15
+ - Integrated P0/P1 bootstrap: line_create queues an onboarding message by default, adds bootstrapOnCreate, and line_status/line_list expose materialized / visibleInSidebar / bootstrapQueued.
16
+ - Kept the 0.3.4 docs and wording; README bootstrap notes were added manually on top of 0.3.4, not overwritten from the older local tree.
17
+ - No schema change; remains v6.
18
+
5
19
  ## 0.3.4 (2026-11-05)
6
20
 
7
21
  - Removed the conflicting suggestion that one-off subtasks should use subagent / Agent Teams.
@@ -63,4 +77,4 @@ English | [中文](CHANGELOG.md)
63
77
  - Explicit `delivered` vs `acked`; at-least-once with effectively-once Session log semantics.
64
78
  - Local filesystem check (NFS/CIFS/SMB/FUSE refused).
65
79
 
66
- Not included: HTTP transport, Web UI, Postgres adapter, automatic process wake.
80
+ Not included: HTTP transport, Web UI, Postgres adapter, automatic process wake.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,20 @@
2
2
 
3
3
  [English](CHANGELOG.en.md) | 中文
4
4
 
5
+ ## 0.3.6 (2026-11-09)
6
+
7
+ - 新增线生命周期:line_retire、line_rebind、line_create replace:true、line_rename。
8
+ - schema v7:lines.title/lifecycle/generation/rebind_at/rebind_from + line_events 审计;旧 DB additive 迁移。
9
+ - 积压迁移:queued/claimed 迁移,delivered/acked 不重投;migrate:none 在 backlog 非空时 fail-closed。
10
+ - 标题持久化:line_create/line_rename 写 lines.title,重启保留。
11
+ - 测试 32/32 通过;旧 0.3.5 行为不变。
12
+
13
+ ## 0.3.5 (2026-11-05)
14
+
15
+ - 集成 P0/P1 bootstrap:line_create 默认排队 onboarding 消息,新增 bootstrapOnCreate,line_status/line_list 暴露 materialized / visibleInSidebar / bootstrapQueued。
16
+ - 保留 0.3.4 的文档与删句;README 以 0.3.4 为基础手工补 bootstrap 说明,没有用本地旧版覆盖。
17
+ - 无 schema 变化,仍为 v6。
18
+
5
19
  ## 0.3.4 (2026-11-05)
6
20
 
7
21
  - 删除与插件定位冲突的提示句:不再在 README / 落地页建议“临时子任务直接用 subagent / Agent Teams”。
@@ -62,4 +76,4 @@
62
76
  - 显式区分 delivered 和 acked;至少一次投递,Session 日志有效一次。
63
77
  - 本地文件系统检查(拒绝 NFS/CIFS/SMB/FUSE)。
64
78
 
65
- 未包含:HTTP transport、Web UI、Postgres adapter、自动拉起进程。
79
+ 未包含:HTTP transport、Web UI、Postgres adapter、自动拉起进程。
package/README.en.md CHANGED
@@ -36,7 +36,7 @@ The script picks the DSH Web profile, installs the plugin, and verifies agent-li
36
36
 
37
37
  Offline or when npm is unavailable, use the local tarball:
38
38
 
39
- bash install.sh ./dsh-agent-lines-0.3.4.tgz
39
+ bash install.sh ./dsh-agent-lines-0.3.6.tgz
40
40
 
41
41
  After install and restart, it works without a config. When you want a fixed manager/worker setup, paste the "Manager config" block below into the file printed by the installer.
42
42
 
@@ -64,6 +64,12 @@ After install and restart, it works without a config. When you want a fixed mana
64
64
 
65
65
  Only `createFrom` may call `line_create`. Worker profiles should leave `allowCreate` false.
66
66
 
67
+ ### New line bootstrap
68
+
69
+ When the manager calls line_create, the plugin queues a no-work onboarding message by default so the blank Session gets its first message and appears in the sidebar; pass bootstrap: false to skip it.
70
+
71
+ line_status / line_list return materialized, visibleInSidebar, and bootstrapQueued; a new line may remain blank until its first message.
72
+
67
73
  ## Quick start
68
74
 
69
75
  1. Run the installer above.
@@ -131,7 +137,10 @@ Tools:
131
137
  | `line_status` | Read-only: current Session binding, manager Session live/persisted, lines, repair command; visible even when unbound |
132
138
  | `line_claim_manager` | Bind this live root Session as manager; requires `allowClaim: true` and `confirm: "bind-manager"`; global, no shell needed |
133
139
  | `line_list` | List lines, status, unread counts, current line and role |
134
- | `line_create` | Manager only: create a DSH Session in the manager workspace (or a named existing workspace) and register it as a line; same label is idempotent |
140
+ | `line_create` | Manager only: create a line; same label is idempotent; replace:true swaps the label to a fresh Session |
141
+ | `line_retire` | Manager only: soft-retire; reject new sends, keep Session and history |
142
+ | `line_rebind` | Manager only: atomically switch a line to a new live Session, optionally migrating backlog |
143
+ | `line_rename` | Manager only: rename the sidebar title and persist it in lines.db |
135
144
  | `line_move_workspace` | Manager only: attach an existing line Session to a workspace whose path exactly matches the Session cwd |
136
145
  | `line_send` | Send to `line` or `agent#line`; optional `idempotencyKey`, `replyTo`, `noReply`, `forceDistinct`, `ttlMs` |
137
146
  | `line_inbox` | Read delivered messages for the current line |
@@ -141,6 +150,17 @@ Line tools other than `line_status` and `line_claim_manager` are registered only
141
150
 
142
151
  `line_create` creates an ordinary DSH Session in the manager workspace (or in the manager cwd when no workspace exists). It does **not** create a separate OS process, profile, or port; all lines in that call share the DSH process. It also does not transfer an existing Session.
143
152
 
153
+ ### Replacing a line when context is full
154
+
155
+ A line does not inherit the old Session context. Recommended flow:
156
+
157
+ 1. Have the old line write a handoff file (line_handoff is available from 0.3.7);
158
+ 2. The manager calls `line_create({ label, replace: true, force: true, reason: "context full" })`;
159
+ 3. The plugin creates a clean Session, atomically swaps the same label, and marks the old Session retired but keeps it;
160
+ 4. queued/claimed messages migrate to the new line; delivered/acked stay on the old Session and are never re-delivered.
161
+
162
+ With `migrate: "none"`, a non-empty queue returns `LINE_BACKLOG_NOT_EMPTY` instead of silently switching.
163
+
144
164
  Created lines are recorded with `created_by` and restored by the manager on process startup. line_create uses the manager's workspace (workspaceId, so DSH attaches the Session) when one exists; otherwise it falls back to the manager cwd and the line is ungrouped. Pass `workspace` (existing path or id) to create in another workspace. A line whose Session was never materialized may fail on first delivery with `session/not-found`; send it a task (or recreate it) to persist the Session.
145
165
 
146
166
  CLI:
@@ -268,4 +288,4 @@ See [CONTRIBUTING.en.md](CONTRIBUTING.en.md); code of conduct [CODE_OF_CONDUCT.e
268
288
 
269
289
  ## License
270
290
 
271
- Apache-2.0. See [LICENSE](LICENSE).
291
+ Apache-2.0. See [LICENSE](LICENSE).
package/README.md CHANGED
@@ -36,7 +36,7 @@ DSH 的 super agent 平替插件。
36
36
 
37
37
  离线或 npm 不可用时,用本地 tarball:
38
38
 
39
- bash install.sh ./dsh-agent-lines-0.3.4.tgz
39
+ bash install.sh ./dsh-agent-lines-0.3.6.tgz
40
40
 
41
41
  安装并重启后,不写配置也可以直接使用;需要固定管理线/worker 时,再把下面“管理线配置”粘贴到脚本打印的配置文件。
42
42
 
@@ -64,6 +64,12 @@ DSH 的 super agent 平替插件。
64
64
 
65
65
  只有 `createFrom` 指定的线能调用 `line_create`。worker profile 不要开 `allowCreate`。
66
66
 
67
+ ### 新线 bootstrap
68
+
69
+ 管理线调用 line_create 创建新线时,插件默认排队一条不要求执行任务的 onboarding 消息,让空白 Session 产生第一条消息并出现在侧栏;传 bootstrap: false 可关闭。
70
+
71
+ line_status / line_list 会返回 materialized、visibleInSidebar、bootstrapQueued;新线在首条消息前可能仍是 blank。
72
+
67
73
  ## 快速开始
68
74
 
69
75
  1. 运行上面的安装脚本。
@@ -131,7 +137,10 @@ line_create({ label: "ops", role: "运维" })
131
137
  | `line_status` | 只读:当前会话绑定、manager Session 是否存在/live、线列表、修复命令;未绑定也可见 |
132
138
  | `line_claim_manager` | 把当前 live 根 Session 绑成 manager;需要 `allowClaim: true` 和 `confirm: "bind-manager"`;全局工具,不需要 shell |
133
139
  | `line_list` | 列出线、状态、未读数、当前线和 role |
134
- | `line_create` | 仅管理线:在管理线工作区(或指定的已有工作区)创建 DSH Session 并注册为线;同 label 幂等 |
140
+ | `line_create` | 仅管理线:创建新线;同 label 幂等;传 replace:true 可给同 label 换新 Session |
141
+ | `line_retire` | 仅管理线:软下线;拒绝新发送,保留 Session/历史 |
142
+ | `line_rebind` | 仅管理线:把线原子切到新的 live Session,可迁移积压 |
143
+ | `line_rename` | 仅管理线:改侧栏标题,持久化到 lines.db |
135
144
  | `line_move_workspace` | 仅管理线:把已有线的 Session 挂到路径完全匹配的工作区 |
136
145
  | `line_send` | 发到 `line` 或 `agent#line`;可选 `idempotencyKey`、`replyTo`、`noReply`、`forceDistinct`、`ttlMs` |
137
146
  | `line_inbox` | 读当前线已投递消息 |
@@ -141,6 +150,17 @@ line_create({ label: "ops", role: "运维" })
141
150
 
142
151
  `line_create` 在管理线所属工作区(没有工作区时回退当前目录)创建普通 DSH Session;它**不会**创建独立 OS 进程、profile 或端口,也不转移已有 Session。
143
152
 
153
+ ### 上下文满时换人
154
+
155
+ 线不会自动继承旧 Session 的上下文。推荐流程:
156
+
157
+ 1. 让旧线写交接单(0.3.7 起可用 `line_handoff`);
158
+ 2. 管理线调用 `line_create({ label, replace: true, force: true, reason: "context full" })`;
159
+ 3. 插件创建干净 Session、同 label 原子切换,旧 Session 标记 retired 但保留;
160
+ 4. queued/claimed 消息迁移到新线;delivered/acked 留在旧 Session,不重投。
161
+
162
+ `migrate: "none"` 时若还有 queued/claimed 会直接报 `LINE_BACKLOG_NOT_EMPTY`,不会静默切走。
163
+
144
164
  创建的线会记录 `created_by`,进程重启时由管理线恢复。line_create 会解析管理线所属工作区并传 workspaceId(DSH 会自动 attach),所以新线出现在该工作区而不是“未分组”;如果管理线本身不在工作区,则回退 cwd,线保持未分组。传 `workspace`(已有路径或 id)可指定其他工作区。若某条线的 Session 还从未落盘,首次投递可能 `session/not-found`;给它发一条任务(或重新创建)即可让它持久化。
145
165
 
146
166
  CLI:
@@ -261,4 +281,4 @@ claim 不会对每个新会话自动执行:需要用户明确要求,或运
261
281
 
262
282
  ## 许可
263
283
 
264
- Apache-2.0,见 [LICENSE](LICENSE)。
284
+ Apache-2.0,见 [LICENSE](LICENSE)。
@@ -98,6 +98,20 @@ The new line is an ordinary DSH Session in the same DSH process; no OS process,
98
98
 
99
99
  `line_move_workspace({ line, workspace })` attaches an existing line Session to an existing workspace. DSH's `attachSession` validates that the Session's stored cwd resolves exactly to the workspace path; a different directory fails with `WORKSPACE_ATTACH_FAILED`. It does not move a Session between different directories. If Session creation succeeds but registration fails, the error carries `detail.sessionId` and the Session is not deleted automatically.
100
100
 
101
+ ## Line lifecycle (0.3.6)
102
+
103
+ line_retire({ line, reason? })
104
+ line_rebind({ line, sessionId, migrate?: "queued" | "none", reason? })
105
+ line_create({ label, replace: true, force?, migrate?, title?, reason? })
106
+ line_rename({ line, title })
107
+
108
+ - retired: line_send returns LINE_RETIRED; the Session and history are kept.
109
+ - rebind: atomically switches lines.session_id and increments generation; the old Session is never deleted.
110
+ - migrate=queued: queued/claimed messages move to the new Session; delivered/acked are never re-delivered.
111
+ - migrate=none: returns LINE_BACKLOG_NOT_EMPTY if the backlog is non-empty.
112
+ - replace: creates a fresh Session for the same label and rebinds; an active line requires force + reason.
113
+ - line_events records title/retire/rebind audit; titles survive restarts.
114
+
101
115
  ## Echo and reply depth
102
116
 
103
117
  - `rootMessageId` groups a reply chain; a root message has null.
@@ -141,4 +155,4 @@ The new line is an ordinary DSH Session in the same DSH process; no OS process,
141
155
  | `LINE_NO_REPLY` | Reply to a noReply message |
142
156
  | `LINE_REPLY_DEPTH_EXCEEDED` | Reply chain exceeds maxReplyDepth |
143
157
  | `LINE_REPLY_TARGET_NOT_FOUND` | replyTo names an unknown message |
144
- | `session/writer-held` (DSH) | Another DSH process holds the target Session's writer lock; close the other view or use a dedicated Session |
158
+ | `session/writer-held` (DSH) | Another DSH process holds the target Session's writer lock; close the other view or use a dedicated Session |
package/docs/PROTOCOL.md CHANGED
@@ -90,6 +90,20 @@ line_create 通过 workspaceRegistry.resolveByPath(managerCwd) 解析管理线
90
90
 
91
91
  line_move_workspace({ line, workspace }) 把已有线 Session 挂到已有工作区。DSH 的 attachSession 要求 Session 存储的 cwd 与工作区 path 完全一致;不同目录会 WORKSPACE_ATTACH_FAILED,不会迁移 Session。如果 Session 创建成功但注册失败,错误里带 detail.sessionId,Session 不会自动删除。
92
92
 
93
+ ## 线生命周期(0.3.6)
94
+
95
+ line_retire({ line, reason? })
96
+ line_rebind({ line, sessionId, migrate?: "queued" | "none", reason? })
97
+ line_create({ label, replace: true, force?, migrate?, title?, reason? })
98
+ line_rename({ line, title })
99
+
100
+ - retired:line_send 返回 LINE_RETIRED;Session 和消息历史保留。
101
+ - rebind:原子切换 lines.session_id,generation+1;旧 Session 不删除。
102
+ - migrate=queued:queued/claimed 迁移到新 Session;delivered/acked 不重投。
103
+ - migrate=none:backlog 非空时返回 LINE_BACKLOG_NOT_EMPTY。
104
+ - replace:同 label 创建新 Session 并 rebind;active 线需 force + reason。
105
+ - line_events 记录 title/retire/rebind 审计;title 持久化,重启保留。
106
+
93
107
  ## 回声与回复深度
94
108
 
95
109
  - rootMessageId 标识回复链;根消息为 null。
@@ -133,4 +147,4 @@ line_move_workspace({ line, workspace }) 把已有线 Session 挂到已有工作
133
147
  | LINE_NO_REPLY | 回复 noReply 消息 |
134
148
  | LINE_REPLY_DEPTH_EXCEEDED | 回复链超过 maxReplyDepth |
135
149
  | LINE_REPLY_TARGET_NOT_FOUND | replyTo 指向未知消息 |
136
- | session/writer-held (DSH) | 另一个 DSH 进程持有目标 Session 的 writer 锁;关闭另一个视图或使用专用 Session |
150
+ | session/writer-held (DSH) | 另一个 DSH 进程持有目标 Session 的 writer 锁;关闭另一个视图或使用专用 Session |
@@ -43,7 +43,7 @@ footer{padding:34px 0 48px;color:var(--muted);font-size:12px}
43
43
  <div class="wrap">
44
44
  <header>
45
45
  <a class="brand" href="../"><span class="mark"></span>dsh-agent-lines</a>
46
- <nav><a href="../">中文</a><a href="https://github.com/Lencen/dsh-agent-lines">GitHub</a><a href="https://github.com/Lencen/dsh-agent-lines/releases/tag/v0.3.4">Release</a></nav>
46
+ <nav><a href="../">中文</a><a href="https://github.com/Lencen/dsh-agent-lines">GitHub</a><a href="https://github.com/Lencen/dsh-agent-lines/releases/tag/v0.3.6">Release</a></nav>
47
47
  </header>
48
48
  <main>
49
49
  <section class="hero" style="border:0;padding-bottom:22px">
@@ -54,7 +54,7 @@ footer{padding:34px 0 48px;color:var(--muted);font-size:12px}
54
54
  <div class="install">curl -fsSL https://raw.githubusercontent.com/Lencen/dsh-agent-lines/main/install.sh -o install.sh &amp;&amp; bash install.sh</div>
55
55
  <div class="actions">
56
56
  <a class="btn primary" href="https://github.com/Lencen/dsh-agent-lines">GitHub repository</a>
57
- <a class="btn" href="https://github.com/Lencen/dsh-agent-lines/releases/tag/v0.3.4">Download 0.3.4</a>
57
+ <a class="btn" href="https://github.com/Lencen/dsh-agent-lines/releases/tag/v0.3.6">Download 0.3.6</a>
58
58
  </div>
59
59
  </div>
60
60
  <div class="shot">
@@ -92,7 +92,7 @@ research (调研), architecture (架构), uiux (UIUX), dev (开发), test (测
92
92
  After the team is ready, wait for my first task. Do not start by yourself.</pre>
93
93
  <p style="color:var(--muted);font-size:14px">Restart DSH Web after install or update. Technical details, protocol, and limits: <a href="https://github.com/Lencen/dsh-agent-lines">README / architecture</a>. Community plugin, not an official DeepSeek product.</p>
94
94
  </section>
95
- <footer>dsh-agent-lines 0.3.4 · Apache-2.0 · Community plugin for DeepSeek Harness. Not an official DeepSeek product.</footer>
95
+ <footer>dsh-agent-lines 0.3.6 · Apache-2.0 · Community plugin for DeepSeek Harness. Not an official DeepSeek product.</footer>
96
96
  </main>
97
97
  </div>
98
98
  </body>
package/docs/index.html CHANGED
@@ -43,7 +43,7 @@ footer{padding:34px 0 48px;color:var(--muted);font-size:12px}
43
43
  <div class="wrap">
44
44
  <header>
45
45
  <a class="brand" href="./"><span class="mark"></span>dsh-agent-lines</a>
46
- <nav><a href="en/index.html">English</a><a href="https://github.com/Lencen/dsh-agent-lines">GitHub</a><a href="https://github.com/Lencen/dsh-agent-lines/releases/tag/v0.3.4">Release</a></nav>
46
+ <nav><a href="en/index.html">English</a><a href="https://github.com/Lencen/dsh-agent-lines">GitHub</a><a href="https://github.com/Lencen/dsh-agent-lines/releases/tag/v0.3.6">Release</a></nav>
47
47
  </header>
48
48
  <main>
49
49
  <section class="hero" style="border:0;padding-bottom:22px">
@@ -54,7 +54,7 @@ footer{padding:34px 0 48px;color:var(--muted);font-size:12px}
54
54
  <div class="install">curl -fsSL https://raw.githubusercontent.com/Lencen/dsh-agent-lines/main/install.sh -o install.sh &amp;&amp; bash install.sh</div>
55
55
  <div class="actions">
56
56
  <a class="btn primary" href="https://github.com/Lencen/dsh-agent-lines">GitHub 仓库</a>
57
- <a class="btn" href="https://github.com/Lencen/dsh-agent-lines/releases/tag/v0.3.4">下载 0.3.4</a>
57
+ <a class="btn" href="https://github.com/Lencen/dsh-agent-lines/releases/tag/v0.3.6">下载 0.3.6</a>
58
58
  </div>
59
59
  </div>
60
60
  <div class="shot">
@@ -92,7 +92,7 @@ research(调研)、architecture(架构)、uiux(UIUX)、dev(开发
92
92
  团队建好后先待命,不要自动开工,等我发第一个任务。</pre>
93
93
  <p style="color:var(--muted);font-size:14px">安装或更新后需要重启 DSH Web。技术细节、协议和限制见 <a href="https://github.com/Lencen/dsh-agent-lines">README / 架构文档</a>。社区插件,不是 DeepSeek 官方产品。</p>
94
94
  </section>
95
- <footer>dsh-agent-lines 0.3.4 · Apache-2.0 · Community plugin for DeepSeek Harness. Not an official DeepSeek product.</footer>
95
+ <footer>dsh-agent-lines 0.3.6 · Apache-2.0 · Community plugin for DeepSeek Harness. Not an official DeepSeek product.</footer>
96
96
  </main>
97
97
  </div>
98
98
  </body>
@@ -50,11 +50,11 @@
50
50
  ]
51
51
  },
52
52
  "dist-tags": {
53
- "latest": "0.3.4"
53
+ "latest": "0.3.6"
54
54
  },
55
55
  "versions": [
56
56
  {
57
- "version": "0.3.4",
57
+ "version": "0.3.6",
58
58
  "publishTimestamp": 1793771000,
59
59
  "source": {
60
60
  "type": "npm"
@@ -50,11 +50,11 @@
50
50
  ]
51
51
  },
52
52
  "dist-tags": {
53
- "latest": "0.3.4"
53
+ "latest": "0.3.6"
54
54
  },
55
55
  "versions": [
56
56
  {
57
- "version": "0.3.4",
57
+ "version": "0.3.6",
58
58
  "publishTimestamp": 1793771000,
59
59
  "source": {
60
60
  "type": "npm"
package/lib/index.js CHANGED
@@ -34,7 +34,8 @@ function normalizeLine(entry, agentId, index) {
34
34
  const sessionId = String(entry.sessionId ?? '').trim()
35
35
  if (sessionId.length === 0) throw new LineError('LINE_INVALID_CONFIG', `lines[${index}].sessionId is required`)
36
36
  const role = entry.role === undefined || entry.role === null ? null : String(entry.role).trim() || null
37
- return { agentId, label, sessionId, lineId: lineId(agentId, label), role }
37
+ const title = entry.title === undefined || entry.title === null ? null : String(entry.title).trim() || null
38
+ return { agentId, label, sessionId, lineId: lineId(agentId, label), role, title }
38
39
  }
39
40
 
40
41
  /** Validate and normalize plugin config. Exported for tests and the CLI. */
@@ -74,6 +75,7 @@ export function normalizeConfig(raw = {}) {
74
75
  maxLines: integer(raw.maxLines, 16, { min: Math.max(1, lines.length), max: 256 }),
75
76
  allowCreate: raw.allowCreate === undefined ? zeroConfig : raw.allowCreate === true,
76
77
  allowClaim: raw.allowClaim === undefined ? zeroConfig : raw.allowClaim === true,
78
+ bootstrapOnCreate: raw.bootstrapOnCreate === undefined ? true : raw.bootstrapOnCreate === true,
77
79
  allowSelfSend: raw.allowSelfSend === true,
78
80
  dedupeWindowMs: integer(raw.dedupeWindowMs, 5_000, { min: 0, max: 3_600_000 }),
79
81
  maxReplyDepth: integer(raw.maxReplyDepth, 8, { min: 1, max: 100 }),
@@ -130,7 +132,7 @@ export async function apply(ctx, rawConfig) {
130
132
  if (def === undefined || bindings.has(agent.session.id)) return
131
133
  const binding = {
132
134
  prompt: bindAgentPrompt(agent, def),
133
- tools: registerToolsForAgent(agent, def, { config, store, lineDefs, createLine, moveLineWorkspace }),
135
+ tools: registerToolsForAgent(agent, def, { config, store, lineDefs, createLine, moveLineWorkspace, retireLine, rebindLine, renameLine }),
134
136
  }
135
137
  bindings.set(agent.session.id, binding)
136
138
  }
@@ -146,10 +148,21 @@ export async function apply(ctx, rawConfig) {
146
148
  }
147
149
  }
148
150
 
151
+ const renameTitle = async (def) => {
152
+ if (def.sessionId === undefined || def.sessionId === '') return
153
+ const title = String(def.title || def.role || def.label || 'agent line').slice(0, 120)
154
+ try {
155
+ await ctx.sessionController?.rename?.({ sessionId: def.sessionId, title })
156
+ } catch (error) {
157
+ ctx.logger?.warn?.('agent-lines: rename %s failed: %s', def.label, String(error))
158
+ }
159
+ }
160
+
149
161
  const startLoop = (def) => {
150
162
  const loop = new DeliveryLoop({ ctx, config: loopConfig(config, def), store, logger: ctx.logger })
151
163
  loops.push(loop)
152
164
  loop.start()
165
+ void renameTitle(def)
153
166
  }
154
167
 
155
168
  const sessionExists = async (sessionId) => {
@@ -280,13 +293,147 @@ export async function apply(ctx, rawConfig) {
280
293
  }
281
294
  process.once('exit', releaseAll)
282
295
 
296
+ const rebinding = new Set()
297
+
298
+ const lineTitle = (def, row) => String((row && row.title) || (def && def.title) || (def && def.role) || (def && def.label) || 'agent line').slice(0, 120)
299
+
300
+ const rebindLine = async ({ label, sessionId, actor, reason, migrate = 'queued', force = false }) => {
301
+ if (label === config.createFrom) throw new LineError('LINE_MANAGER_REBIND_UNSUPPORTED', 'The manager line is rebound with line_claim_manager, not line_rebind', { line: label })
302
+ const row = store.getLineRow(config.agentId, label)
303
+ if (row === undefined) throw new LineError('LINE_NOT_FOUND', `No such line: ${config.agentId}#${label}`)
304
+ if (rebinding.has(label) || row.lifecycle === 'rebinding') throw new LineError('LINE_REBIND_BUSY', `Line ${label} is already rebinding`, { line: label })
305
+ if (!(await sessionExists(sessionId))) throw new LineError('LINE_SESSION_NOT_FOUND', `Session is not live or persisted: ${sessionId}`, { sessionId })
306
+ const target = lineDefs.get(sessionId)
307
+ if (target !== undefined && target.label !== label) throw new LineError('LINE_SESSION_BOUND', `Session ${sessionId} is already bound to ${target.label}`, { sessionId, line: target.label })
308
+ const oldDef = [...lineDefs.values()].find(line => line.label === label)
309
+ if (oldDef !== undefined && oldDef.sessionId === sessionId) {
310
+ return { line: label, oldSessionId: row.session_id, newSessionId: sessionId, generation: row.generation, counts: store.messageCounts({ agentId: config.agentId, line: label }), already: true }
311
+ }
312
+ const oldLifecycle = row.lifecycle || 'active'
313
+ const oldAgent = oldDef === undefined ? undefined : ctx.agents.get(oldDef.sessionId)
314
+ rebinding.add(label)
315
+ let locked = false
316
+ try {
317
+ store.setLifecycle({ agentId: config.agentId, line: label, lifecycle: 'rebinding', actor, reason })
318
+ locked = true
319
+ await stopLoopFor(label)
320
+ if (oldDef !== undefined) lineDefs.delete(oldDef.sessionId)
321
+ if (oldAgent !== undefined) unbindAgent(oldAgent)
322
+ const updated = store.rebind({
323
+ agentId: config.agentId, line: label, sessionId, actor, reason, migrate, locked: true,
324
+ })
325
+ const def = {
326
+ agentId: config.agentId, label, sessionId, lineId: lineId(config.agentId, label),
327
+ role: (oldDef && oldDef.role) || row.role || null,
328
+ title: lineTitle(oldDef, updated), createdBy: row.created_by || (oldDef && oldDef.createdBy) || null,
329
+ lifecycle: 'active', generation: updated.generation,
330
+ }
331
+ lineDefs.set(sessionId, def)
332
+ startLoop(def)
333
+ const agent = ctx.agents.get(sessionId)
334
+ if (agent !== undefined) bindAgent(agent)
335
+ return { line: label, oldSessionId: row.session_id, newSessionId: sessionId, generation: updated.generation, counts: updated.counts }
336
+ } catch (error) {
337
+ try { await stopLoopFor(label) } catch { /* best effort */ }
338
+ if (oldDef !== undefined) {
339
+ lineDefs.set(oldDef.sessionId, oldDef)
340
+ startLoop(oldDef)
341
+ const agent = ctx.agents.get(oldDef.sessionId)
342
+ if (agent !== undefined) bindAgent(agent)
343
+ }
344
+ if (locked) {
345
+ try { store.setLifecycle({ agentId: config.agentId, line: label, lifecycle: oldLifecycle === 'rebinding' ? 'active' : oldLifecycle, actor, reason: 'rebind rollback' }) } catch { /* best effort */ }
346
+ }
347
+ throw error
348
+ } finally {
349
+ rebinding.delete(label)
350
+ }
351
+ }
352
+
353
+ const retireLine = async ({ label, actor, reason }) => {
354
+ if (label === config.createFrom) throw new LineError('LINE_MANAGER_RETIRE_UNSUPPORTED', 'The manager line cannot be retired', { line: label })
355
+ const row = store.getLineRow(config.agentId, label)
356
+ if (row === undefined) throw new LineError('LINE_NOT_FOUND', `No such line: ${config.agentId}#${label}`)
357
+ const def = [...lineDefs.values()].find(line => line.label === label)
358
+ if (def !== undefined) def.lifecycle = 'retired'
359
+ await stopLoopFor(label)
360
+ const updated = store.retire({ agentId: config.agentId, line: label, actor, reason })
361
+ return { line: label, lifecycle: updated.lifecycle, counts: updated.counts, already: row.lifecycle === 'retired' }
362
+ }
363
+
364
+ const renameLine = async ({ label, title, actor }) => {
365
+ const row = store.getLineRow(config.agentId, label)
366
+ if (row === undefined) throw new LineError('LINE_NOT_FOUND', `No such line: ${config.agentId}#${label}`)
367
+ const updated = store.setTitle({ agentId: config.agentId, line: label, title, actor })
368
+ const def = [...lineDefs.values()].find(line => line.label === label)
369
+ if (def !== undefined) def.title = updated.title
370
+ try { await ctx.sessionController?.rename?.({ sessionId: row.session_id, title: updated.title || title }) } catch { /* blank session can rename later */ }
371
+ return { line: label, title: updated.title }
372
+ }
373
+
374
+ const replaceLine = async (existing, args, exec) => {
375
+ if (existing.label === config.createFrom) throw new LineError('LINE_MANAGER_REBIND_UNSUPPORTED', 'The manager line cannot be replaced', { line: existing.label })
376
+ if (existing.lifecycle === 'active' && args.force !== true) {
377
+ throw new LineError('LINE_REPLACE_ACTIVE', `Line ${existing.label} is active; pass force:true to replace it`, { line: existing.label, lifecycle: existing.lifecycle })
378
+ }
379
+ if (args.migrate === 'none') {
380
+ const backlog = store.messageCounts({ agentId: config.agentId, line: existing.label })
381
+ if (backlog.queued + backlog.claimed > 0) {
382
+ throw new LineError('LINE_BACKLOG_NOT_EMPTY', `Line ${existing.label} has ${backlog.queued + backlog.claimed} queued/claimed messages`, { line: existing.label, counts: backlog })
383
+ }
384
+ }
385
+ const baseCwd = exec?.agent?.session?.header?.cwd ?? process.cwd()
386
+ if (args.workspace !== undefined && args.cwd !== undefined) throw new LineError('LINE_INVALID_ARGUMENT', 'workspace and cwd are mutually exclusive')
387
+ const cwd = args.cwd === undefined || String(args.cwd).trim() === '' ? baseCwd : resolve(baseCwd, String(args.cwd).trim())
388
+ const targetWorkspace = args.workspace !== undefined ? await resolveWorkspace(args.workspace) : await managerWorkspace(baseCwd)
389
+ const role = args.role === undefined || args.role === null ? null : String(args.role).trim() || null
390
+ const title = args.title === undefined || args.title === null ? (role || existing.title || existing.role || existing.label) : String(args.title).trim().slice(0, 120)
391
+ const sessionId = `session-${randomUUID()}`
392
+ const created = await ctx.sessionController.create({
393
+ sessionId,
394
+ ...(targetWorkspace === undefined ? { cwd } : { workspaceId: targetWorkspace.id }),
395
+ agentPreset: args.agentPreset === undefined ? config.childPreset : String(args.agentPreset),
396
+ })
397
+ const actualSessionId = created.sessionId
398
+ const result = await rebindLine({
399
+ label: existing.label, sessionId: actualSessionId, actor: (exec && exec.agent && exec.agent.session && exec.agent.session.id) || null,
400
+ reason: String(args.reason || 'line_create replace'), migrate: args.migrate === 'none' ? 'none' : 'queued', force: args.force === true,
401
+ })
402
+ const newDef = lineDefs.get(actualSessionId)
403
+ if (newDef !== undefined) {
404
+ newDef.role = role
405
+ newDef.title = title
406
+ try { store.setTitle({ agentId: config.agentId, line: existing.label, title }) } catch { /* best effort */ }
407
+ }
408
+ let bootstrapQueued = false
409
+ if (args.bootstrap !== false && config.bootstrapOnCreate !== false) {
410
+ const creator = lineDefs.get(exec.agent.session.id)
411
+ if (creator !== undefined) {
412
+ try {
413
+ store.send({
414
+ agentId: config.agentId, fromLine: creator.label, to: existing.label,
415
+ text: `[Agent Line] ${existing.label} replaced. You are ${role ?? existing.role ?? existing.label}. Read the handoff file before starting; this is an identity message, do not modify files yet.`,
416
+ noReply: true, maxReplyDepth: config.maxReplyDepth, maxMessageBytes: config.maxMessageBytes,
417
+ })
418
+ bootstrapQueued = true
419
+ } catch (error) { ctx.logger?.warn?.('agent-lines: replace bootstrap failed: %s', String(error)) }
420
+ }
421
+ }
422
+ return {
423
+ line: existing.label, sessionId: actualSessionId, oldSessionId: result.oldSessionId,
424
+ role, title, created: true, replaced: true, generation: result.generation, counts: result.counts,
425
+ cwd: targetWorkspace?.path ?? cwd, workspaceId: targetWorkspace?.id ?? null, bootstrapQueued,
426
+ }
427
+ }
428
+
283
429
  const createLine = async (args, exec) => {
284
430
  if (closed) throw new LineError('LINE_CLOSED', 'The agent-lines plugin is shutting down')
285
431
  if (!config.allowCreate) throw new LineError('LINE_CREATE_DISABLED', 'line_create is disabled by config')
286
432
  const label = validateLineLabel(args.label)
287
433
  const existing = store.getLineRow(config.agentId, label)
288
434
  if (existing !== undefined) {
289
- return { line: existing.label, sessionId: existing.session_id, role: existing.role, created: false }
435
+ if (args.replace === true) return replaceLine(existing, args, exec)
436
+ return { line: existing.label, sessionId: existing.session_id, role: existing.role, title: existing.title ?? existing.role ?? existing.label, lifecycle: existing.lifecycle, created: false }
290
437
  }
291
438
  if (store.countLines(config.agentId) >= config.maxLines) {
292
439
  throw new LineError('LINE_LIMIT', `Line limit reached: ${config.maxLines}`, { maxLines: config.maxLines })
@@ -302,6 +449,7 @@ export async function apply(ctx, rawConfig) {
302
449
  ? await resolveWorkspace(args.workspace)
303
450
  : await managerWorkspace(baseCwd)
304
451
  const role = args.role === undefined || args.role === null ? null : String(args.role).trim() || null
452
+ const title = args.title === undefined || args.title === null ? (role || label) : String(args.title).trim().slice(0, 120)
305
453
  const sessionId = `session-${randomUUID()}`
306
454
  const created = await ctx.sessionController.create({
307
455
  sessionId,
@@ -310,7 +458,7 @@ export async function apply(ctx, rawConfig) {
310
458
  })
311
459
  const creator = lineDefs.get(exec.agent.session.id)
312
460
  const actualSessionId = created.sessionId
313
- const def = { agentId: config.agentId, label, sessionId: actualSessionId, lineId: lineId(config.agentId, label), role, createdBy: creator?.lineId ?? null }
461
+ const def = { agentId: config.agentId, label, sessionId: actualSessionId, lineId: lineId(config.agentId, label), role, title, createdBy: creator?.lineId ?? null, lifecycle: 'active', generation: 1 }
314
462
  try {
315
463
  store.acquire({
316
464
  agentId: config.agentId,
@@ -328,14 +476,44 @@ export async function apply(ctx, rawConfig) {
328
476
  ctx.logger?.warn?.('agent-lines: created Session %s but failed to register line %s', actualSessionId, label)
329
477
  throw error
330
478
  }
479
+ try { store.setTitle({ agentId: config.agentId, line: label, title }) } catch { /* title is best-effort after acquire */ }
331
480
  lineDefs.set(actualSessionId, def)
332
481
  startLoop(def)
333
482
  const agent = ctx.agents.get(actualSessionId)
334
483
  if (agent !== undefined) bindAgent(agent)
335
- try {
336
- await ctx.sessionController.rename({ sessionId: actualSessionId, title: `line: ${label}` })
337
- } catch { /* a blank session may not materialize on rename; first delivery will */ }
338
- return { line: label, sessionId: actualSessionId, role, cwd: targetWorkspace?.path ?? cwd, workspaceId: targetWorkspace?.id ?? null, created: true }
484
+ let bootstrapQueued = false
485
+ if (args.bootstrap !== false && config.bootstrapOnCreate !== false && creator !== undefined) {
486
+ try {
487
+ store.send({
488
+ agentId: config.agentId,
489
+ fromLine: creator.label,
490
+ to: label,
491
+ text: `[Agent Line] ${label} onboarding. You are ${role ?? label}. This is an identity message: do not start work and do not modify files. Acknowledge briefly if needed, then wait for the manager's first task.`,
492
+ noReply: true,
493
+ maxReplyDepth: config.maxReplyDepth,
494
+ maxMessageBytes: config.maxMessageBytes,
495
+ })
496
+ bootstrapQueued = true
497
+ } catch (error) {
498
+ ctx.logger?.warn?.('agent-lines: line %s created but onboarding bootstrap failed: %s', label, String(error))
499
+ }
500
+ }
501
+ return {
502
+ line: label,
503
+ sessionId: actualSessionId,
504
+ role,
505
+ title,
506
+ lifecycle: 'active',
507
+ cwd: targetWorkspace?.path ?? cwd,
508
+ workspaceId: targetWorkspace?.id ?? null,
509
+ created: true,
510
+ materialized: false,
511
+ visibleInSidebar: false,
512
+ bootstrapQueued,
513
+ hint: bootstrapQueued
514
+ ? 'Onboarding message queued; the Session becomes visible after its first turn.'
515
+ : 'No bootstrap queued; send a standby message or refresh after the first delivery.',
516
+ }
339
517
  }
340
518
 
341
519
  try {
@@ -353,6 +531,11 @@ export async function apply(ctx, rawConfig) {
353
531
  ctx.logger?.info?.('agent-lines: manager %s is unbound; waiting for claim', def.label)
354
532
  continue
355
533
  }
534
+ const stored = store.getLineRow(config.agentId, def.label)
535
+ if (stored !== undefined && stored.lifecycle !== 'active') {
536
+ ctx.logger?.info?.('agent-lines: line %s is %s; skipping delivery loop', def.label, stored.lifecycle)
537
+ continue
538
+ }
356
539
  if (!(await sessionExists(def.sessionId))) {
357
540
  ctx.logger?.warn?.('agent-lines: Session %s for line %s is missing; line stays unbound until claimed', def.sessionId, def.label)
358
541
  lineDefs.set(def.sessionId, { ...def, missing: true })
@@ -366,8 +549,9 @@ export async function apply(ctx, rawConfig) {
366
549
  ttlMs: config.leaseTtlMs,
367
550
  role: def.role,
368
551
  })
369
- lineDefs.set(def.sessionId, def)
370
- startLoop(def)
552
+ const effective = { ...def, title: lineTitle(def, stored), lifecycle: 'active', generation: Number(stored?.generation ?? 1) }
553
+ lineDefs.set(def.sessionId, effective)
554
+ startLoop(effective)
371
555
  }
372
556
  cleanupFns.push(ctx.on('agent/created', ({ agent }) => { bindAgent(agent) }))
373
557
  cleanupFns.push(ctx.on('agent/disposed', ({ agent }) => { unbindAgent(agent) }))
@@ -375,6 +559,7 @@ export async function apply(ctx, rawConfig) {
375
559
  const managerLineId = lineId(config.agentId, config.createFrom)
376
560
  for (const row of store.listLines()) {
377
561
  if (row.created_by !== managerLineId || lineDefs.has(row.session_id)) continue
562
+ if (row.lifecycle !== 'active') continue
378
563
  if (!(await sessionExists(row.session_id))) {
379
564
  ctx.logger?.warn?.('agent-lines: dynamic line %s has no persisted Session; skipped restore', row.label)
380
565
  continue
@@ -389,7 +574,7 @@ export async function apply(ctx, rawConfig) {
389
574
  role: row.role,
390
575
  createdBy: row.created_by,
391
576
  })
392
- const def = { agentId: config.agentId, label: row.label, sessionId: row.session_id, lineId: row.line_id, role: row.role, createdBy: row.created_by }
577
+ const def = { agentId: config.agentId, label: row.label, sessionId: row.session_id, lineId: row.line_id, role: row.role, title: lineTitle({ role: row.role, label: row.label }, row), createdBy: row.created_by, lifecycle: 'active', generation: Number(row.generation ?? 1) }
393
578
  lineDefs.set(row.session_id, def)
394
579
  startLoop(def)
395
580
  } catch (error) {
@@ -438,4 +623,4 @@ export async function apply(ctx, rawConfig) {
438
623
  store.close()
439
624
  throw error
440
625
  }
441
- }
626
+ }
package/lib/store.js CHANGED
@@ -33,10 +33,15 @@ CREATE TABLE IF NOT EXISTS lines (
33
33
  agent_id TEXT NOT NULL,
34
34
  label TEXT NOT NULL,
35
35
  role TEXT,
36
+ title TEXT,
36
37
  created_by TEXT,
37
38
  session_id TEXT NOT NULL,
38
39
  instance_id TEXT,
39
40
  status TEXT NOT NULL DEFAULT 'offline',
41
+ lifecycle TEXT NOT NULL DEFAULT 'active',
42
+ generation INTEGER NOT NULL DEFAULT 1,
43
+ rebind_at INTEGER,
44
+ rebind_from TEXT,
40
45
  last_seen INTEGER NOT NULL DEFAULT 0,
41
46
  created_at INTEGER NOT NULL,
42
47
  UNIQUE(agent_id, label)
@@ -97,7 +102,20 @@ CREATE TABLE IF NOT EXISTS manager_bindings (
97
102
  updated_at INTEGER NOT NULL
98
103
  );
99
104
 
100
- PRAGMA user_version = 6;
105
+ CREATE TABLE IF NOT EXISTS line_events (
106
+ id TEXT PRIMARY KEY,
107
+ line_id TEXT NOT NULL,
108
+ action TEXT NOT NULL,
109
+ old_session_id TEXT,
110
+ new_session_id TEXT,
111
+ actor TEXT,
112
+ reason TEXT,
113
+ detail TEXT,
114
+ created_at INTEGER NOT NULL
115
+ );
116
+ CREATE INDEX IF NOT EXISTS line_events_line ON line_events(line_id, created_at);
117
+
118
+ PRAGMA user_version = 7;
101
119
  `
102
120
 
103
121
  export function defaultDbPath() {
@@ -140,12 +158,19 @@ export class LineStore {
140
158
  this.db.exec(SCHEMA)
141
159
  const columns = this.db.prepare('PRAGMA table_info(lines)').all().map(column => column.name)
142
160
  if (!columns.includes('role')) this.db.exec('ALTER TABLE lines ADD COLUMN role TEXT')
161
+ if (!columns.includes('title')) this.db.exec('ALTER TABLE lines ADD COLUMN title TEXT')
143
162
  if (!columns.includes('created_by')) this.db.exec('ALTER TABLE lines ADD COLUMN created_by TEXT')
163
+ if (!columns.includes('lifecycle')) this.db.exec("ALTER TABLE lines ADD COLUMN lifecycle TEXT NOT NULL DEFAULT 'active'")
164
+ if (!columns.includes('generation')) this.db.exec('ALTER TABLE lines ADD COLUMN generation INTEGER NOT NULL DEFAULT 1')
165
+ if (!columns.includes('rebind_at')) this.db.exec('ALTER TABLE lines ADD COLUMN rebind_at INTEGER')
166
+ if (!columns.includes('rebind_from')) this.db.exec('ALTER TABLE lines ADD COLUMN rebind_from TEXT')
144
167
  const messageColumns = this.db.prepare('PRAGMA table_info(messages)').all().map(column => column.name)
145
168
  if (!messageColumns.includes('root_message_id')) this.db.exec('ALTER TABLE messages ADD COLUMN root_message_id TEXT')
146
169
  if (!messageColumns.includes('hop')) this.db.exec('ALTER TABLE messages ADD COLUMN hop INTEGER NOT NULL DEFAULT 0')
147
170
  if (!messageColumns.includes('no_reply')) this.db.exec('ALTER TABLE messages ADD COLUMN no_reply INTEGER NOT NULL DEFAULT 0')
148
- this.db.exec('PRAGMA user_version = 6')
171
+ this.db.exec('CREATE TABLE IF NOT EXISTS line_events (id TEXT PRIMARY KEY, line_id TEXT NOT NULL, action TEXT NOT NULL, old_session_id TEXT, new_session_id TEXT, actor TEXT, reason TEXT, detail TEXT, created_at INTEGER NOT NULL)')
172
+ this.db.exec('CREATE INDEX IF NOT EXISTS line_events_line ON line_events(line_id, created_at)')
173
+ this.db.exec('PRAGMA user_version = 7')
149
174
  this.prepared = new Map()
150
175
  this.closed = false
151
176
  this.fresh = fresh
@@ -244,6 +269,8 @@ export class LineStore {
244
269
  const from = this.#stmt('SELECT * FROM lines WHERE agent_id = ? AND label = ?').get(agentId, fromLine)
245
270
  if (from === undefined) throw new LineError('LINE_NOT_FOUND', `Sender line is not registered: ${agentId}#${fromLine}`)
246
271
  const target = this.resolveTarget(agentId, to)
272
+ if (target.row.lifecycle === 'retired') throw new LineError('LINE_RETIRED', `Line ${target.lineId} is retired`, { line: target.lineId })
273
+ if (target.row.lifecycle === 'rebinding') throw new LineError('LINE_REBINDING', `Line ${target.lineId} is rebinding`, { line: target.lineId })
247
274
  const body = assertMessageSize(text, maxMessageBytes)
248
275
  let parent
249
276
  if (replyTo !== undefined && replyTo !== null && String(replyTo).trim() !== '') {
@@ -413,6 +440,111 @@ export class LineStore {
413
440
  }
414
441
  }
415
442
 
443
+ /** Update the display title of a line. Persisted so restarts keep it. */
444
+ setTitle({ agentId, line, title, actor = null, now = Date.now() }) {
445
+ const id = lineId(agentId, line)
446
+ return this.#tx(() => {
447
+ const row = this.#stmt('SELECT * FROM lines WHERE line_id = ?').get(id)
448
+ if (row === undefined) throw new LineError('LINE_NOT_FOUND', `No such line: ${id}`, { line: id })
449
+ const value = title === null || title === undefined ? null : String(title).trim().slice(0, 120) || null
450
+ this.#stmt('UPDATE lines SET title = ? WHERE line_id = ?').run(value, id)
451
+ this.#event({ lineId: id, action: 'title', actor, detail: { title: value }, now })
452
+ return { ...this.#stmt('SELECT * FROM lines WHERE line_id = ?').get(id) }
453
+ })
454
+ }
455
+
456
+ /** Set lifecycle without a Session rebind (used to lock a rebind in progress). */
457
+ setLifecycle({ agentId, line, lifecycle, actor = null, reason = null, now = Date.now() }) {
458
+ const id = lineId(agentId, line)
459
+ if (!['active', 'retired', 'rebinding'].includes(String(lifecycle))) {
460
+ throw new LineError('LINE_INVALID_LIFECYCLE', `Invalid lifecycle: ${lifecycle}`)
461
+ }
462
+ return this.#tx(() => {
463
+ const row = this.#stmt('SELECT * FROM lines WHERE line_id = ?').get(id)
464
+ if (row === undefined) throw new LineError('LINE_NOT_FOUND', `No such line: ${id}`, { line: id })
465
+ this.#stmt("UPDATE lines SET lifecycle = ?, status = CASE WHEN ? = 'active' THEN status ELSE 'offline' END WHERE line_id = ?")
466
+ .run(String(lifecycle), String(lifecycle), id)
467
+ this.#event({ lineId: id, action: lifecycle, actor, reason, now })
468
+ return { ...this.#stmt('SELECT * FROM lines WHERE line_id = ?').get(id) }
469
+ })
470
+ }
471
+
472
+ /** Queue/claimed/delivered counts for one line. */
473
+ messageCounts({ agentId, line }) {
474
+ const rows = this.#stmt(`SELECT state, COUNT(*) AS n FROM messages
475
+ WHERE to_agent = ? AND to_line = ? GROUP BY state`).all(agentId, line)
476
+ const out = { queued: 0, claimed: 0, delivered: 0, acked: 0, failed: 0, expired: 0, dead: 0 }
477
+ for (const row of rows) out[row.state] = Number(row.n)
478
+ return out
479
+ }
480
+
481
+ /** Retire a line: no new sends, keep Session/queue/history. */
482
+ retire({ agentId, line, actor = null, reason = null, now = Date.now() }) {
483
+ const id = lineId(agentId, line)
484
+ return this.#tx(() => {
485
+ const row = this.#stmt('SELECT * FROM lines WHERE line_id = ?').get(id)
486
+ if (row === undefined) throw new LineError('LINE_NOT_FOUND', `No such line: ${id}`, { line: id })
487
+ if (row.lifecycle !== 'retired') {
488
+ this.#stmt("UPDATE lines SET lifecycle = 'retired', status = 'offline' WHERE line_id = ?").run(id)
489
+ this.#event({ lineId: id, action: 'retire', actor, reason, detail: this.messageCounts({ agentId, line }), now })
490
+ }
491
+ return { ...this.#stmt('SELECT * FROM lines WHERE line_id = ?').get(id), counts: this.messageCounts({ agentId, line }) }
492
+ })
493
+ }
494
+
495
+ /**
496
+ * Atomically switch a line to a new Session.
497
+ * migrate=queued: requeue claimed messages; queued/claimed will be delivered by the new loop.
498
+ * migrate=none: fail-closed if queued+claimed > 0 (manager must drain first).
499
+ * delivered/acked/failed/expired are never re-delivered.
500
+ */
501
+ rebind({ agentId, line, sessionId, actor = null, reason = null, migrate = 'queued', locked = false, now = Date.now() }) {
502
+ const id = lineId(agentId, line)
503
+ if (!['queued', 'none'].includes(String(migrate))) {
504
+ throw new LineError('LINE_INVALID_ARGUMENT', `migrate must be queued or none: ${migrate}`)
505
+ }
506
+ return this.#tx(() => {
507
+ const row = this.#stmt('SELECT * FROM lines WHERE line_id = ?').get(id)
508
+ if (row === undefined) throw new LineError('LINE_NOT_FOUND', `No such line: ${id}`, { line: id })
509
+ if (row.lifecycle === 'rebinding' && locked !== true) throw new LineError('LINE_REBIND_BUSY', `Line ${id} is already rebinding`, { line: id })
510
+ const counts = this.messageCounts({ agentId, line })
511
+ if (String(migrate) === 'none' && counts.queued + counts.claimed > 0) {
512
+ throw new LineError('LINE_BACKLOG_NOT_EMPTY', `Line ${id} has ${counts.queued + counts.claimed} queued/claimed messages; drain or use migrate=queued`, { line: id, counts })
513
+ }
514
+ if (String(migrate) === 'queued') {
515
+ this.#stmt(`UPDATE messages SET state = 'queued', claimed_by = NULL, claimed_at = NULL, next_attempt_at = ?
516
+ WHERE to_agent = ? AND to_line = ? AND state = 'claimed'`).run(now, agentId, line)
517
+ }
518
+ this.#stmt('DELETE FROM leases WHERE line_id = ?').run(id)
519
+ const generation = Number(row.generation ?? 1) + 1
520
+ this.#stmt(`UPDATE lines SET session_id = ?, lifecycle = 'active', generation = ?, rebind_at = ?, rebind_from = ?,
521
+ instance_id = NULL, status = 'offline', last_seen = ? WHERE line_id = ?`)
522
+ .run(String(sessionId), generation, now, row.session_id, now, id)
523
+ const detail = { migrate: String(migrate), before: counts, after: this.messageCounts({ agentId, line }), generation }
524
+ this.#event({ lineId: id, action: 'rebind', oldSessionId: row.session_id, newSessionId: String(sessionId), actor, reason, detail, now })
525
+ return { ...this.#stmt('SELECT * FROM lines WHERE line_id = ?').get(id), oldSessionId: row.session_id, counts: detail.after }
526
+ })
527
+ }
528
+
529
+ /** Last rebind event for a line (used to show oldSessionId without overwriting the row). */
530
+ lastLineEvent({ agentId, line, action = 'rebind' }) {
531
+ const id = lineId(agentId, line)
532
+ return this.#stmt('SELECT * FROM line_events WHERE line_id = ? AND action = ? ORDER BY created_at DESC LIMIT 1').get(id, action)
533
+ }
534
+
535
+ /** Recent lifecycle events for diagnostics. */
536
+ lineEvents({ agentId, line, limit = 20 }) {
537
+ const id = lineId(agentId, line)
538
+ return this.#stmt('SELECT * FROM line_events WHERE line_id = ? ORDER BY created_at DESC LIMIT ?').all(id, limit)
539
+ }
540
+
541
+ #event({ lineId: target, action, oldSessionId = null, newSessionId = null, actor = null, reason = null, detail = null, now = Date.now() }) {
542
+ const id = 'lineev_' + randomUUID().replaceAll('-', '')
543
+ this.#stmt(`INSERT INTO line_events(id, line_id, action, old_session_id, new_session_id, actor, reason, detail, created_at)
544
+ VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(id, target, action, oldSessionId, newSessionId, actor, reason, detail === null ? null : JSON.stringify(detail), now)
545
+ return id
546
+ }
547
+
416
548
  counts(now = Date.now()) {
417
549
  const states = this.#stmt('SELECT state, COUNT(*) AS n FROM messages GROUP BY state ORDER BY state').all()
418
550
  const leases = this.#stmt('SELECT COUNT(*) AS n FROM leases WHERE expires_at > ?').get(now)
@@ -421,4 +553,4 @@ export class LineStore {
421
553
  }
422
554
  }
423
555
 
424
- export { expandHome }
556
+ export { expandHome }
package/lib/tools.js CHANGED
@@ -37,9 +37,21 @@ function limitValue(value, fallback, max) {
37
37
  return number
38
38
  }
39
39
 
40
+ function materializationOf(ctx, sessionId) {
41
+ const live = ctx.agents.get(sessionId)
42
+ if (live === undefined) return null
43
+ const projections = ctx.get?.('sessionProjections')
44
+ if (projections?.snapshot === undefined) return null
45
+ try {
46
+ const meta = projections.snapshot(live.session, ['sessionListMetadata'])?.values?.sessionListMetadata
47
+ return meta === undefined ? null : meta.blank === false
48
+ } catch { return null }
49
+ }
50
+
40
51
  function currentView(def) {
41
52
  return def === undefined ? null : {
42
53
  agentId: def.agentId, line: def.label, sessionId: def.sessionId, lineId: def.lineId, role: def.role,
54
+ title: def.title ?? def.role ?? def.label, lifecycle: def.lifecycle ?? 'active', generation: def.generation ?? 1,
43
55
  }
44
56
  }
45
57
 
@@ -83,10 +95,14 @@ export function registerStatusTool(ctx, { config, store, lineDefs }) {
83
95
  const lines = store.listLines().map(line => ({
84
96
  label: line.label,
85
97
  role: line.role,
98
+ title: line.title ?? line.role ?? line.label,
99
+ lifecycle: line.lifecycle ?? 'active',
100
+ generation: line.generation ?? 1,
86
101
  sessionId: line.session_id,
87
102
  createdBy: line.created_by,
88
103
  lease: line.lease,
89
104
  live: ctx.agents.get(line.session_id) !== undefined,
105
+ materialized: materializationOf(ctx, line.session_id),
90
106
  }))
91
107
  const current = currentId === undefined
92
108
  ? null
@@ -95,6 +111,8 @@ export function registerStatusTool(ctx, { config, store, lineDefs }) {
95
111
  bound: currentDef !== undefined,
96
112
  line: currentDef?.label ?? null,
97
113
  role: currentDef?.role ?? null,
114
+ title: currentDef?.title ?? currentDef?.role ?? null,
115
+ lifecycle: currentDef?.lifecycle ?? null,
98
116
  }
99
117
  const repair = current === null
100
118
  ? 'No calling Session; line_status is informational.'
@@ -103,7 +121,7 @@ export function registerStatusTool(ctx, { config, store, lineDefs }) {
103
121
  : config.allowClaim
104
122
  ? `Current Session is not bound. Call line_claim_manager({ confirm: "bind-manager" }) to bind this root Session.`
105
123
  : `Current Session is not bound. Run: dsh-agent-lines claim --agent ${config.agentId} --line ${config.createFrom} --session ${currentId} (set allowClaim: true first)`
106
- return { current, manager, lines, allowClaim: config.allowClaim, repair }
124
+ return { current, manager, lines, allowClaim: config.allowClaim, bootstrapOnCreate: config.bootstrapOnCreate, repair }
107
125
  },
108
126
  })
109
127
  }
@@ -145,7 +163,7 @@ export function registerClaimTool(ctx, { config, lineDefs, rebindManager }) {
145
163
  }
146
164
 
147
165
  /** Register the model tools; returns their disposers. */
148
- export function registerToolsForAgent(agent, def, { config, store, lineDefs, createLine, moveLineWorkspace }) {
166
+ export function registerToolsForAgent(agent, def, { config, store, lineDefs, createLine, moveLineWorkspace, retireLine, rebindLine, renameLine }) {
149
167
  const disposers = []
150
168
 
151
169
  disposers.push(agent.ctx.tools.register({
@@ -155,7 +173,11 @@ export function registerToolsForAgent(agent, def, { config, store, lineDefs, cre
155
173
  output: OUTPUT,
156
174
  execute: async (_args, exec) => {
157
175
  const current = lineDefs.get(exec?.agent?.session?.id)
158
- return { current: currentView(current), lines: store.listLines() }
176
+ return {
177
+ current: currentView(current),
178
+ lines: store.listLines().map(line => ({ ...line, live: agent.ctx.agents.get(line.session_id) !== undefined, materialized: materializationOf(agent.ctx, line.session_id) })),
179
+ bootstrapOnCreate: config.bootstrapOnCreate,
180
+ }
159
181
  },
160
182
  }))
161
183
 
@@ -179,6 +201,7 @@ export function registerToolsForAgent(agent, def, { config, store, lineDefs, cre
179
201
  output: OUTPUT,
180
202
  execute: async (args, exec) => {
181
203
  const def = currentLine(exec, lineDefs)
204
+ if (def.lifecycle === 'retired') throw new LineError('LINE_RETIRED', `Line ${def.label} is retired; it cannot send new messages`, { line: def.label })
182
205
  const text = assertMessageSize(args.text, config.maxMessageBytes)
183
206
  const target = parseTarget(args.to, def.agentId)
184
207
  if (target.lineId === def.lineId && config.allowSelfSend !== true) {
@@ -268,16 +291,22 @@ export function registerToolsForAgent(agent, def, { config, store, lineDefs, cre
268
291
  if (config.allowCreate === true && def.label === config.createFrom) {
269
292
  disposers.push(agent.ctx.tools.register({
270
293
  name: 'line_create',
271
- description: 'Create a new independent DSH Session in this process and register it as an agent line, so it can be addressed with line_send. Only the configured manager line (createFrom) may call this. Reusing an existing label returns created:false without creating a Session. This does not create a separate OS process or transfer an existing Session.',
294
+ description: 'Create a new independent DSH Session in this process and register it as an agent line, so it can be addressed with line_send. Only the configured manager line (createFrom) may call this. Reusing an existing label returns created:false without creating a Session. By default the plugin queues a no-work onboarding message so the Session becomes non-blank and appears in the sidebar; pass bootstrap:false to skip it.',
272
295
  parameters: {
273
296
  type: 'object',
274
297
  additionalProperties: false,
275
298
  properties: {
276
299
  label: { type: 'string', description: 'Stable line label, e.g. "frontend-line"' },
277
300
  role: { type: 'string', description: 'Short role or responsibility description for the new line' },
301
+ title: { type: 'string', description: 'Sidebar title; defaults to role or label' },
302
+ replace: { type: 'boolean', description: 'Replace an existing line with a fresh Session; old Session is retired (manager only)' },
303
+ force: { type: 'boolean', description: 'Allow replacing an active line; use with reason' },
304
+ migrate: { type: 'string', enum: ['queued', 'none'], description: 'Backlog policy on replace; none fails if queued/claimed exists' },
305
+ reason: { type: 'string', description: 'Reason for replace; shown in line_events' },
278
306
  agentPreset: { type: 'string', description: 'DSH agent preset; defaults to the plugin childPreset' },
279
307
  workspace: { type: 'string', description: 'Target workspace path or id; defaults to the manager workspace. Existing workspace only.' },
280
308
  cwd: { type: 'string', description: 'Working directory when no workspace is named; defaults to the manager Session cwd' },
309
+ bootstrap: { type: 'boolean', description: 'Queue a no-work onboarding message so the new Session appears in the sidebar; defaults to config.bootstrapOnCreate' },
281
310
  },
282
311
  required: ['label'],
283
312
  },
@@ -293,6 +322,67 @@ export function registerToolsForAgent(agent, def, { config, store, lineDefs, cre
293
322
  },
294
323
  }))
295
324
 
325
+ disposers.push(agent.ctx.tools.register({
326
+ name: 'line_retire',
327
+ description: 'Retire an existing line: new line_send is rejected, the Session and message history are kept, and the delivery loop stops. Only the configured manager line may call this. Use line_create replace:true to hand the same role to a fresh Session.',
328
+ parameters: {
329
+ type: 'object', additionalProperties: false,
330
+ properties: {
331
+ line: { type: 'string', description: 'Existing line label' },
332
+ reason: { type: 'string', description: 'Why this line is being retired' },
333
+ },
334
+ required: ['line'],
335
+ },
336
+ output: OUTPUT,
337
+ execute: async (args, exec) => {
338
+ const caller = currentLine(exec, lineDefs)
339
+ if (caller.label !== config.createFrom) throw new LineError('LINE_CREATE_FORBIDDEN', `Only ${config.createFrom} may retire lines`, { caller: caller.label })
340
+ return retireLine({ label: String(args.line), actor: caller.label, reason: args.reason ?? null })
341
+ },
342
+ }))
343
+
344
+ disposers.push(agent.ctx.tools.register({
345
+ name: 'line_rebind',
346
+ description: 'Atomically switch an existing line to a new live Session, migrating queued/claimed messages. The old Session is kept, never deleted. Only the configured manager line may call this; use line_create replace:true to create a fresh Session in one step.',
347
+ parameters: {
348
+ type: 'object', additionalProperties: false,
349
+ properties: {
350
+ line: { type: 'string', description: 'Existing line label' },
351
+ sessionId: { type: 'string', description: 'Live root Session id to bind' },
352
+ migrate: { type: 'string', enum: ['queued', 'none'], description: 'queued migrates queued/claimed; none fails if backlog is non-empty' },
353
+ reason: { type: 'string', description: 'Why this line is being rebound' },
354
+ force: { type: 'boolean', description: 'Accepted for API compatibility; active replacement is gated by line_create replace' },
355
+ },
356
+ required: ['line', 'sessionId'],
357
+ },
358
+ output: OUTPUT,
359
+ execute: async (args, exec) => {
360
+ const caller = currentLine(exec, lineDefs)
361
+ if (caller.label !== config.createFrom) throw new LineError('LINE_CREATE_FORBIDDEN', `Only ${config.createFrom} may rebind lines`, { caller: caller.label })
362
+ return rebindLine({ label: String(args.line), sessionId: String(args.sessionId), actor: caller.label, reason: args.reason ?? null, migrate: args.migrate === 'none' ? 'none' : 'queued', force: args.force === true })
363
+ },
364
+ }))
365
+
366
+ disposers.push(agent.ctx.tools.register({
367
+ name: 'line_rename',
368
+ description: 'Rename a line display title in the sidebar. The title is persisted in lines.db and survives restarts. Only the configured manager line may call this.',
369
+ parameters: {
370
+ type: 'object', additionalProperties: false,
371
+ properties: {
372
+ line: { type: 'string', description: 'Existing line label' },
373
+ title: { type: 'string', description: 'New title, 1-120 chars' },
374
+ },
375
+ required: ['line', 'title'],
376
+ },
377
+ output: OUTPUT,
378
+ execute: async (args, exec) => {
379
+ const caller = currentLine(exec, lineDefs)
380
+ if (caller.label !== config.createFrom) throw new LineError('LINE_CREATE_FORBIDDEN', `Only ${config.createFrom} may rename lines`, { caller: caller.label })
381
+ if (String(args.title ?? '').trim() === '') throw new LineError('LINE_INVALID_ARGUMENT', 'title must not be empty')
382
+ return renameLine({ label: String(args.line), title: String(args.title), actor: caller.label })
383
+ },
384
+ }))
385
+
296
386
  disposers.push(agent.ctx.tools.register({
297
387
  name: 'line_move_workspace',
298
388
  description: 'Move an existing line Session into a target workspace record so it appears under that workspace in the sidebar. DSH only allows attachment when the Session cwd exactly matches the workspace path; it cannot move a Session to a different directory (use a new line for that).',
@@ -317,4 +407,4 @@ export function registerToolsForAgent(agent, def, { config, store, lineDefs, cre
317
407
  }
318
408
 
319
409
  return disposers
320
- }
410
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-agent-lines",
3
- "version": "0.3.4",
3
+ "version": "0.3.6",
4
4
  "description": "DSH Agent 的持久、可寻址消息线(社区插件)。",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",