dsh-deep-ptc-mode 1.9.6 → 1.9.7

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.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.9.7 — 2026-11-17
4
+
5
+ - 卡片改为插件自己的实现:会话投影保存卡片、宿主命令处理按钮、`conversation.chat.turnTail` 渲染、新增 `ui_card` 工具负责创建/更新/删除。不再依赖宿主 `actionCards` 的 `propose_action`——那个工具是“按需动态声明”的,进不了深度 PTC 的 `run_code` 工具集,卡片因此无法在 PTC 会话里出现。现在与 Skill 卡片同一套机制,在 PTC 和其它会话里都能用。
6
+ - 卡片按钮执行真实动作:删除卡片指定的定时任务、运行一条命令(30 秒超时);执行中/成功/失败三态直接显示在卡片上。
7
+ - 移除 1.9.6 的 action-card 种类、技能与客户端 body(改用 `ui_card` 工具),并新增纯逻辑单测。
8
+ - Cards now use the plugin's own mechanism: a session projection holds them, a host command handles the button, `conversation.chat.turnTail` renders them, and a new `ui_card` tool creates, updates and removes them. The host's `actionCards` `propose_action` is no longer used: that tool is declared conditionally and never reaches Deep PTC's `run_code` tool set, so cards could not appear in PTC sessions. This is the same mechanism the skill card uses, so cards work in PTC and elsewhere.
9
+ - A card button really runs: it deletes the scheduled tasks the card names and runs one command (30s timeout); working/done/failed states render on the card itself.
10
+ - Removes 1.9.6's action-card kind, skill and client body in favour of `ui_card`, and adds unit tests for the pure card logic.
11
+
3
12
  ## 1.9.6 — 2026-11-17
4
13
 
5
14
  - 新增「小卡片」:插件向宿主注册一个通用操作卡片种类(`deep-ptc-card`),模型可以在回答下方留一张静态卡片——标题、键值行、脚注——卡片上的按钮由宿主真正执行:删除指定的定时任务,或运行一条命令。卡片用宿主原生的 action-cards 界面渲染,不遮挡输入框;未注册 body 的宿主会退化成只有「暂不」的兜底卡片,不影响其他功能。
@@ -0,0 +1,164 @@
1
+ // Runtime for conversation cards.
2
+ //
3
+ // Cards are first-class plugin state: a session projection stores them, a host
4
+ // command applies their one action, and a plugin-owned tool lets the model leave
5
+ // one. Nothing here depends on a host card service, so it also works where only
6
+ // the plugin's own tools reach the agent.
7
+
8
+ import { exec } from 'node:child_process';
9
+ import { importHost } from './host.mjs';
10
+ import { CARD_COMMAND, CARD_TOOL, CARDS_EVENT, CARDS_KEY, blankCards, addCard, foldCardsState, parseCardsState,
11
+ readCardInput, removeCard, withCard, FAILED, OPEN, STOPPED, STOPPING } from './cards.mjs';
12
+
13
+ export const name = 'deep-ptc-cards';
14
+ // Optional layer: a missing service disables the cards rather than the preset.
15
+ export const inject = [];
16
+ const REQUIRED = ['commands', 'sessionProjections', 'tools'];
17
+ const STOP_TIMEOUT_MS = 30_000;
18
+ const MAX_REASON = 300;
19
+
20
+ export function apply(ctx) {
21
+ // Starts once the host services exist; the caller never holds the boot for it.
22
+ return ctx.plugin({ name: 'deep-ptc-cards-layer', inject: REQUIRED, apply: install }).await()
23
+ .catch(error => ctx.logger.warn('Deep PTC: conversation cards are off (%s)', error.message));
24
+ }
25
+
26
+ /** The session module's plugin-record writer; injectable so the card path runs in tests. */
27
+ export async function sessionRecords() {
28
+ const { appendPluginRecord } = await importHost('@deepseek-ai/dsh-session');
29
+ if (typeof appendPluginRecord !== 'function') throw new Error('the installed session module has no appendPluginRecord');
30
+ return appendPluginRecord;
31
+ }
32
+
33
+ export async function install(ctx, records = sessionRecords) {
34
+ const appendPluginRecord = await records();
35
+ const schema = { parse: parseCardsState };
36
+ const projection = await ctx.sessionProjections.register({ key: CARDS_KEY, stateVersion: 1,
37
+ stateSchema: schema, init: blankCards, apply: foldCardsState,
38
+ wire: { viewSchema: schema, view: state => state, summary: false } });
39
+ ctx.effect(() => () => projection.dispose());
40
+ const save = (session, state) => appendPluginRecord(session, CARDS_EVENT, state);
41
+ const read = session => projection.stateOf(session) ?? blankCards();
42
+
43
+ ctx.commands.register({ name: CARD_COMMAND, recordInput: false,
44
+ description: '处理对话卡片上的一个操作 / Apply one action to a conversation card',
45
+ handler: ({ agent, rawInput }) => act(ctx, agent, rawInput, read, save) });
46
+
47
+ ctx.effect(() => ctx.tools.register({
48
+ name: CARD_TOOL,
49
+ description: 'Leave one small card in the conversation: a title, labelled rows, an optional note and one optional action button. Use it when the user wants a card or control panel kept in the conversation. Cards stay until the user stops or dismisses them. Call again with the same id to update a card, or with action "remove" to delete one.',
50
+ parameters: { type: 'object', additionalProperties: false, properties: {
51
+ action: { type: 'string', enum: ['show', 'remove'], description: 'show adds or updates a card; remove deletes one by id.' },
52
+ id: { type: 'string', description: 'Optional stable id; reuse it to update the same card.' },
53
+ title: { type: 'string', description: 'Card title.' },
54
+ subtitle: { type: 'string', description: 'One small line under the title.' },
55
+ lines: { type: 'array', items: { type: 'object', additionalProperties: false,
56
+ properties: { label: { type: 'string' }, value: { type: 'string' } }, required: ['label', 'value'] },
57
+ description: 'Up to 12 labelled rows.' },
58
+ note: { type: 'string', description: 'Footnote, up to 400 characters.' },
59
+ tone: { type: 'string', enum: ['info', 'warn'], description: 'Card tone.' },
60
+ stop: { type: 'object', additionalProperties: false, description: 'The card button: what pressing it really does.',
61
+ properties: {
62
+ label: { type: 'string', description: 'Button text, defaults to 停止.' },
63
+ command: { type: 'string', description: 'Command to run on the host, 30 second timeout.' },
64
+ schedules: { type: 'array', items: { type: 'string' }, description: 'Scheduled task ids to delete.' },
65
+ } },
66
+ }, required: ['action'] },
67
+ output: { schema: {}, render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }] },
68
+ async execute(args, exec) {
69
+ const session = exec.agent?.session;
70
+ if (!session) throw new Error('No active conversation');
71
+ const state = read(session);
72
+ if (args.action === 'remove') {
73
+ const id = typeof args.id === 'string' ? args.id : '';
74
+ if (!state.cards.some(row => row.id === id)) throw new Error('Unknown card id');
75
+ save(session, { ...state, cards: state.cards.filter(row => row.id !== id) });
76
+ return { removed: id };
77
+ }
78
+ const parsed = readCardInput(args);
79
+ if (parsed.issues !== undefined) throw new Error(parsed.issues.join('; '));
80
+ const id = typeof args.id === 'string' && args.id !== '' ? args.id : undefined;
81
+ const added = addCard(state, parsed.card, id);
82
+ save(session, added.state);
83
+ return { id: added.card.id, phase: added.card.phase,
84
+ cards: added.state.cards.map(row => ({ id: row.id, title: row.title, phase: row.phase })) };
85
+ },
86
+ }), 'Deep PTC: card tool');
87
+ }
88
+
89
+ /** Apply one card action; the card shows its result while the work finishes. */
90
+ function act(ctx, agent, rawInput, read, save) {
91
+ const session = agent?.session;
92
+ if (!session) return { kind: 'error', text: 'No active conversation. / 当前没有活动对话。' };
93
+ const request = parseCommand(rawInput);
94
+ if (request === undefined) return { kind: 'error', text: 'Invalid card action. / 无效的卡片操作。' };
95
+ const state = read(session);
96
+ const card = state.cards.find(row => row.id === request.id);
97
+ if (card === undefined) return { kind: 'error', text: 'Unknown card. / 未知的卡片。' };
98
+ if (card.phase !== OPEN) return { kind: 'success', text: 'Card already closed. / 卡片已处理。' };
99
+ if (request.action === 'dismiss') {
100
+ save(session, removeCard(state, card.id));
101
+ return { kind: 'success', text: 'Card closed. / 卡片已关闭。' };
102
+ }
103
+ save(session, withCard(state, card.id, { phase: STOPPING }));
104
+ void runAction(ctx, session, card, read, save);
105
+ return { kind: 'success', text: 'Card action started. / 卡片操作已开始。' };
106
+ }
107
+
108
+ function parseCommand(rawInput) {
109
+ let request;
110
+ try { request = JSON.parse(String(rawInput ?? '')); } catch { return undefined; }
111
+ if (request === null || typeof request !== 'object' || Array.isArray(request)) return undefined;
112
+ const id = typeof request.id === 'string' ? request.id : '';
113
+ if (id === '' || id.length > 64) return undefined;
114
+ if (request.action !== 'stop' && request.action !== 'dismiss') return undefined;
115
+ return { id, action: request.action };
116
+ }
117
+
118
+ /** Run the card's action: delete its scheduled tasks, then its command. */
119
+ async function runAction(ctx, session, card, read, save) {
120
+ const result = { schedules: [] };
121
+ const errors = [];
122
+ const stop = card.stop;
123
+ if (stop === undefined) errors.push('no action');
124
+ const schedule = stop?.schedules === undefined ? undefined : ctx.get('schedule');
125
+ for (const id of stop?.schedules ?? []) {
126
+ if (schedule === undefined) {
127
+ errors.push('schedule service unavailable');
128
+ break;
129
+ }
130
+ try {
131
+ await schedule.edit({ id, action: 'delete' }, session.id);
132
+ result.schedules.push(id);
133
+ } catch (error) {
134
+ errors.push('schedule ' + id + ': ' + reason(error));
135
+ ctx.logger.warn('Deep PTC: could not delete schedule %s (%s)', id, error.message);
136
+ }
137
+ }
138
+ if (stop?.command !== undefined) {
139
+ try {
140
+ await run(stop.command);
141
+ result.command = 'ok';
142
+ } catch (error) {
143
+ result.command = 'failed';
144
+ errors.push('command: ' + reason(error));
145
+ ctx.logger.warn('Deep PTC: card command failed (%s)', error.message);
146
+ }
147
+ }
148
+ if (errors.length > 0) result.errors = errors;
149
+ const next = withCard(read(session), card.id, { phase: errors.length === 0 ? STOPPED : FAILED, result });
150
+ save(session, next);
151
+ }
152
+
153
+ function reason(error) {
154
+ return String(error?.message ?? error).trim().slice(0, MAX_REASON);
155
+ }
156
+
157
+ function run(command) {
158
+ return new Promise((resolve, reject) => {
159
+ exec(command, { timeout: STOP_TIMEOUT_MS, windowsHide: true, maxBuffer: 1 << 20 }, (error, _stdout, stderr) => {
160
+ if (error === null) resolve();
161
+ else reject(new Error(String(stderr ?? '').trim().split('\n')[0].slice(0, MAX_REASON) || error.message));
162
+ });
163
+ });
164
+ }
package/lib/cards.mjs ADDED
@@ -0,0 +1,177 @@
1
+ // Pure state and view logic for conversation cards.
2
+ //
3
+ // A card is a small panel the model leaves in the conversation: a title, labelled
4
+ // rows, a note and one optional action. The card lives in the session log, so it
5
+ // survives turns, and the client renders it at the end of the latest turn.
6
+
7
+ export const CARDS_KEY = 'deepPtcCards';
8
+ export const CARDS_EVENT = 'plugin:dsh-deep-ptc-mode/cards';
9
+ export const CARD_COMMAND = 'deep-ptc-card-act';
10
+ export const CARD_TOOL = 'ui_card';
11
+
12
+ export const OPEN = 'open';
13
+ export const STOPPING = 'stopping';
14
+ export const STOPPED = 'stopped';
15
+ export const FAILED = 'failed';
16
+ export const DISMISSED = 'dismissed';
17
+
18
+ const MAX_CARDS = 8;
19
+ const MAX_ID = 64;
20
+ const MAX_TITLE = 120;
21
+ const MAX_SUBTITLE = 160;
22
+ const MAX_LABEL = 40;
23
+ const MAX_VALUE = 300;
24
+ const MAX_LINES = 12;
25
+ const MAX_NOTE = 400;
26
+ const MAX_STOP_LABEL = 24;
27
+ const MAX_COMMAND = 2000;
28
+ const MAX_SCHEDULES = 8;
29
+ const MAX_SCHEDULE_ID = 120;
30
+
31
+ const objects = value => value !== null && typeof value === 'object' && !Array.isArray(value);
32
+ const text = (value, max) => typeof value === 'string' ? value.trim().slice(0, max) : '';
33
+
34
+ export function blankCards() {
35
+ return { v: 1, seq: 0, cards: [] };
36
+ }
37
+
38
+ function readLines(value, issues) {
39
+ if (value === undefined) return [];
40
+ if (!Array.isArray(value) || value.length > MAX_LINES) {
41
+ issues.push('lines: use at most ' + MAX_LINES + ' rows');
42
+ return [];
43
+ }
44
+ const rows = [];
45
+ value.forEach((row, index) => {
46
+ const label = text(row?.label, MAX_LABEL);
47
+ if (!objects(row) || label === '') {
48
+ issues.push('lines.' + index + ': every row needs a label');
49
+ return;
50
+ }
51
+ rows.push({ label, value: text(row.value, MAX_VALUE) });
52
+ });
53
+ return rows;
54
+ }
55
+
56
+ function readStop(value, issues) {
57
+ if (value === undefined) return undefined;
58
+ if (!objects(value)) {
59
+ issues.push('stop: expected an object');
60
+ return undefined;
61
+ }
62
+ const stop = {};
63
+ const label = text(value.label, MAX_STOP_LABEL);
64
+ if (label !== '') stop.label = label;
65
+ const command = text(value.command, MAX_COMMAND);
66
+ if (command !== '') stop.command = command;
67
+ if (value.schedules !== undefined) {
68
+ if (!Array.isArray(value.schedules) || value.schedules.length > MAX_SCHEDULES) {
69
+ issues.push('stop.schedules: use at most ' + MAX_SCHEDULES + ' ids');
70
+ } else {
71
+ const ids = value.schedules.map(id => text(id, MAX_SCHEDULE_ID)).filter(id => id !== '');
72
+ if (ids.length > 0) stop.schedules = ids;
73
+ }
74
+ }
75
+ if (stop.command === undefined && stop.schedules === undefined) {
76
+ issues.push('stop: a command or schedule ids are required');
77
+ return undefined;
78
+ }
79
+ return stop;
80
+ }
81
+
82
+ /** Normalise one tool call into a card, or list what the model must fix. */
83
+ export function readCardInput(value) {
84
+ if (!objects(value)) return { issues: ['expected an object'] };
85
+ const issues = [];
86
+ const card = { title: text(value.title, MAX_TITLE) };
87
+ if (card.title === '') issues.push('title: required');
88
+ const subtitle = text(value.subtitle, MAX_SUBTITLE);
89
+ if (subtitle !== '') card.subtitle = subtitle;
90
+ const lines = readLines(value.lines, issues);
91
+ if (lines.length > 0) card.lines = lines;
92
+ const note = text(value.note, MAX_NOTE);
93
+ if (note !== '') card.note = note;
94
+ if (value.tone === 'warn') card.tone = 'warn';
95
+ else if (value.tone !== undefined && value.tone !== 'info') issues.push('tone: use info or warn');
96
+ const stop = readStop(value.stop, issues);
97
+ if (stop !== undefined) card.stop = stop;
98
+ if (issues.length > 0) return { issues };
99
+ if (card.subtitle === undefined && card.lines === undefined && card.note === undefined) {
100
+ return { issues: ['a card needs a subtitle, lines or a note'] };
101
+ }
102
+ return { card };
103
+ }
104
+
105
+ function readCard(row) {
106
+ if (!objects(row) || typeof row.id !== 'string' || row.id === '' || row.id.length > MAX_ID
107
+ || typeof row.title !== 'string' || row.title === '' || row.title.length > MAX_TITLE
108
+ || typeof row.phase !== 'string' || ![OPEN, STOPPING, STOPPED, FAILED, DISMISSED].includes(row.phase)) {
109
+ throw new Error('Invalid Deep PTC card');
110
+ }
111
+ const card = { id: row.id, title: row.title, phase: row.phase };
112
+ if (typeof row.subtitle === 'string' && row.subtitle !== '') card.subtitle = row.subtitle.slice(0, MAX_SUBTITLE);
113
+ if (Array.isArray(row.lines)) card.lines = row.lines.filter(objects).slice(0, MAX_LINES)
114
+ .map(line => ({ label: text(line.label, MAX_LABEL), value: text(line.value, MAX_VALUE) }));
115
+ if (typeof row.note === 'string' && row.note !== '') card.note = row.note.slice(0, MAX_NOTE);
116
+ if (row.tone === 'warn') card.tone = 'warn';
117
+ if (objects(row.stop)) {
118
+ const stop = {};
119
+ if (typeof row.stop.label === 'string') stop.label = row.stop.label.slice(0, MAX_STOP_LABEL);
120
+ if (typeof row.stop.command === 'string') stop.command = row.stop.command.slice(0, MAX_COMMAND);
121
+ if (Array.isArray(row.stop.schedules)) stop.schedules = row.stop.schedules.filter(id => typeof id === 'string').slice(0, MAX_SCHEDULES);
122
+ if (stop.command !== undefined || (stop.schedules ?? []).length > 0) card.stop = stop;
123
+ }
124
+ if (objects(row.result)) card.result = {
125
+ ...(Array.isArray(row.result.schedules) ? { schedules: row.result.schedules.filter(id => typeof id === 'string') } : {}),
126
+ ...(typeof row.result.command === 'string' ? { command: row.result.command } : {}),
127
+ ...(Array.isArray(row.result.errors) ? { errors: row.result.errors.filter(item => typeof item === 'string').map(item => item.slice(0, MAX_VALUE)) } : {}),
128
+ };
129
+ return card;
130
+ }
131
+
132
+ /** Validate one durable card state (also the wire view the client reads). */
133
+ export function parseCardsState(value) {
134
+ if (!objects(value) || value.v !== 1 || !Number.isSafeInteger(value.seq) || value.seq < 0
135
+ || !Array.isArray(value.cards) || value.cards.length > MAX_CARDS) throw new Error('Invalid Deep PTC card state');
136
+ const cards = value.cards.map(readCard);
137
+ if (new Set(cards.map(card => card.id)).size !== cards.length) throw new Error('Duplicate Deep PTC card id');
138
+ return { v: 1, seq: value.seq, cards };
139
+ }
140
+
141
+ /** Fold one session event into the card state. */
142
+ export function foldCardsState(state, event) {
143
+ if (event.type !== CARDS_EVENT) return state;
144
+ try { return parseCardsState(event.data); } catch { return state; }
145
+ }
146
+
147
+ /** Add or replace one card; a repeated id updates the same card in place. */
148
+ export function addCard(state, card, id) {
149
+ const next = state.cards.find(row => row.id === id || (id === undefined && row.title === card.title));
150
+ if (next !== undefined) {
151
+ const replaced = { ...next, ...card, id: next.id, phase: OPEN, result: undefined };
152
+ return { state: { ...state, cards: state.cards.map(row => row.id === next.id ? replaced : row) }, card: replaced };
153
+ }
154
+ const seq = state.seq + 1;
155
+ const created = { ...card, id: id ?? 'card-' + seq, phase: OPEN };
156
+ return { state: { ...state, seq, cards: [...state.cards, created].slice(-MAX_CARDS) }, card: created };
157
+ }
158
+
159
+ /** Drop one card from the conversation. */
160
+ export function removeCard(state, id) {
161
+ return { ...state, cards: state.cards.filter(row => row.id !== id) };
162
+ }
163
+
164
+ /** Mark one card and keep the rest untouched. */
165
+ export function withCard(state, id, patch) {
166
+ return { ...state, cards: state.cards.map(row => row.id === id ? { ...row, ...patch } : row) };
167
+ }
168
+
169
+ /** The result the client shows after an action settles. */
170
+ export function cardSummary(card) {
171
+ const parts = [];
172
+ const schedules = card.result?.schedules ?? [];
173
+ if (schedules.length > 0) parts.push('schedules: ' + schedules.length);
174
+ if (card.result?.command !== undefined) parts.push('command: ' + card.result.command);
175
+ if ((card.result?.errors ?? []).length > 0) parts.push('errors: ' + card.result.errors.length);
176
+ return parts.join('; ');
177
+ }
package/lib/client.js CHANGED
@@ -216,9 +216,8 @@ window.__ModuleLoader__.load({ id: 'dsh-deep-ptc-mode', factory: require => {
216
216
  skillHint: '关闭的 Skill 会在你发送下一条消息时移出上下文,历史记录不受影响。',
217
217
  skillKeepAll: '全部保留', skillCloseAll: '全部关闭', skillNoDescription: '无描述', skillThisTurn: '本轮',
218
218
  skillShowAll: '显示全部 {count} 个', skillShowLess: '收起',
219
- acardStop: '停止', acardDismiss: '知道了', acardStopped: '已执行', acardFailed: '执行失败',
220
- acardDismissed: '已关闭', acardDone: '已处理',
221
- acardTransport: '没有收到结果,请重连后检查这张卡片。', acardUnavailable: '这张卡片现在不可用。',
219
+ cardLabel: '对话卡片', cardStopDefault: '停止', cardDismiss: '关闭',
220
+ cardStopping: '正在处理…', cardStopped: '已执行', cardFailed: '执行失败', cardDismissed: '已关闭',
222
221
  agentsTitle: '子代理',
223
222
  agentRunning: '运行中', agentCompleted: '已完成', agentIdle: '空闲', agentExternal: '外部',
224
223
  agentOpen: '在右侧栏打开这个子代理的对话',
@@ -252,9 +251,8 @@ window.__ModuleLoader__.load({ id: 'dsh-deep-ptc-mode', factory: require => {
252
251
  skillHint: 'A closed skill leaves the model context when you send your next message. The history stays complete.',
253
252
  skillKeepAll: 'Keep all', skillCloseAll: 'Close all', skillNoDescription: 'No description', skillThisTurn: 'this turn',
254
253
  skillShowAll: 'Show all {count}', skillShowLess: 'Show less',
255
- acardStop: 'Stop', acardDismiss: 'Done', acardStopped: 'Done', acardFailed: 'Failed',
256
- acardDismissed: 'Dismissed', acardDone: 'Handled',
257
- acardTransport: 'No result arrived; reconnect and check this card.', acardUnavailable: 'This card is no longer available.',
254
+ cardLabel: 'Conversation cards', cardStopDefault: 'Stop', cardDismiss: 'Dismiss',
255
+ cardStopping: 'Working…', cardStopped: 'Done', cardFailed: 'Failed', cardDismissed: 'Dismissed',
258
256
  agentsTitle: 'Subagents',
259
257
  agentRunning: 'Running', agentCompleted: 'Done', agentIdle: 'Idle', agentExternal: 'External',
260
258
  agentOpen: 'Open this subagent in the right sidebar',
@@ -483,7 +481,10 @@ ${ON}[data-dpt-busy] [data-dpt-send]::after{content:"";position:absolute;inset:-
483
481
  .dpt-ripple{position:fixed;z-index:2147483000;pointer-events:none;width:20px;height:20px;margin:-10px 0 0 -10px;border-radius:50%;border:2px solid color-mix(in srgb,var(--dpt-brand,#3370ff) 75%,transparent);background:radial-gradient(circle,color-mix(in srgb,var(--dpt-brand,#3370ff) 45%,transparent),color-mix(in srgb,var(--dpt-brand,#3370ff) 12%,transparent) 60%,transparent 72%);animation:dpt-ripple 650ms cubic-bezier(.22,1,.36,1) forwards}
484
482
  @keyframes dpt-ripple{0%{transform:scale(.3);opacity:1}100%{transform:scale(7);opacity:0}}
485
483
  .dpt-fx{position:fixed;left:0;top:0;z-index:2147482000;pointer-events:none;-webkit-app-region:initial!important}
486
- .dpt-acard{display:flex;flex-direction:column;gap:8px}
484
+ .dpt-cards{display:flex;flex-direction:column;gap:8px;margin:2px 0 4px}
485
+ .dpt-acard{display:flex;flex-direction:column;gap:8px;box-sizing:border-box;padding:12px 14px;border:.5px solid var(--dsw-alias-border-l2,#d6dce6);border-radius:12px;background:var(--dsw-static-neutral-50,#f7f8fa)}
486
+ .dpt-acard-head{display:flex;flex-direction:column;gap:2px}
487
+ .dpt-acard-title{font-weight:600;line-height:20px}
487
488
  .dpt-acard-sub{font-size:12px;line-height:18px;color:var(--dsw-alias-label-tertiary,#667085)}
488
489
  .dpt-acard[data-tone="warn"] .dpt-acard-sub{color:var(--dsw-alias-state-warn-primary,#b45309)}
489
490
  .dpt-acard-lines{display:flex;flex-direction:column;gap:4px;margin:0}
@@ -946,40 +947,54 @@ ${ON}[data-dpt-busy] [data-dpt-send]::after{content:"";position:absolute;inset:-
946
947
  }
947
948
 
948
949
  // ---------------------------------------------------------------------------------------------
949
- // Action card body: the small card the user asked for, rendered under the answer. The host kind
950
- // owns the stop action; this body draws the card's own fields and turns its verb into a button.
950
+ // Conversation cards. They are plugin state, not host cards: the model leaves one through the
951
+ // plugin's own tool, the projection stores it in the session log, and the button runs a host
952
+ // command. They render at the end of the latest turn, in the page flow.
951
953
  // ---------------------------------------------------------------------------------------------
952
- const ACARD_PHASES = { stopped: 'acardStopped', failed: 'acardFailed', dismissed: 'acardDismissed' };
954
+ const CARD_COMMAND_NAME = 'deep-ptc-card-act';
955
+ const CARD_PHASES = { stopping: 'cardStopping', stopped: 'cardStopped', failed: 'cardFailed', dismissed: 'cardDismissed' };
953
956
 
954
- function ActionCardBody({ proposal, decision, act, t }) {
955
- const [pending, setPending] = React.useState(false);
956
- const [error, setError] = React.useState();
957
- const details = proposal?.details ?? {};
958
- const lines = Array.isArray(details.lines) ? details.lines : [];
959
- const phase = typeof decision?.phase === 'string' ? decision.phase : undefined;
960
- async function run(verb) {
961
- setPending(true);
962
- setError(undefined);
963
- try {
964
- const result = await act(verb);
965
- if (result === undefined) setError('acardTransport');
966
- else if (result.status === 'refused' || result.status === 'unconfirmed') setError('acardUnavailable');
967
- } catch { setError('acardTransport'); } finally { setPending(false); }
968
- }
969
- const stop = details.stop;
970
- return h('div', { className: 'dpt-acard', 'data-tone': details.tone === 'warn' ? 'warn' : undefined },
971
- details.subtitle ? h('div', { className: 'dpt-acard-sub' }, details.subtitle) : null,
972
- lines.length > 0 ? h('dl', { className: 'dpt-acard-lines' }, ...lines.map((row, index) => h('div', { key: index, className: 'dpt-acard-line' },
957
+ function CardCommandRow({ node, t }) {
958
+ const outcome = node?.outcome;
959
+ if (outcome?.kind === 'error') return h('div', { className: 'dpt-command-error', role: 'status' }, commandText(outcome.text, t));
960
+ return h('span', { hidden: true, 'data-dpt-hidden-command': CARD_COMMAND_NAME });
961
+ }
962
+
963
+ function runCardCommand(child, sessionId, payload) {
964
+ const execute = child.remote?.commands?.execute;
965
+ if (typeof execute !== 'function') return Promise.resolve({ ok: false, error: { message: 'unavailable' } });
966
+ return execute(sessionId, `/${CARD_COMMAND_NAME} ` + JSON.stringify(payload), []);
967
+ }
968
+
969
+ function CardView({ card, run, pending, t }) {
970
+ const rows = Array.isArray(card.lines) ? card.lines : [];
971
+ const done = CARD_PHASES[card.phase];
972
+ return h('section', { className: 'dpt-acard', 'data-tone': card.tone === 'warn' ? 'warn' : undefined, 'aria-label': card.title },
973
+ h('div', { className: 'dpt-acard-head' },
974
+ h('span', { className: 'dpt-acard-title' }, card.title),
975
+ card.subtitle ? h('span', { className: 'dpt-acard-sub' }, card.subtitle) : null),
976
+ rows.length > 0 ? h('dl', { className: 'dpt-acard-lines' }, ...rows.map((row, index) => h('div', { key: index, className: 'dpt-acard-line' },
973
977
  h('dt', null, row.label), h('dd', null, row.value)))) : null,
974
- details.note ? h('p', { className: 'dpt-acard-note' }, details.note) : null,
975
- error ? h('p', { className: 'dpt-acard-error', role: 'alert' }, t(error)) : null,
976
- phase !== undefined
977
- ? h('p', { className: 'dpt-acard-done', role: 'status' }, t(ACARD_PHASES[phase] ?? 'acardDone'))
978
- : h('div', { className: 'dpt-acard-actions' },
979
- stop ? h('button', { type: 'button', className: 'dpt-acard-btn', disabled: pending, 'aria-busy': pending,
980
- onClick: () => { void run('stop'); } }, stop.label ?? t('acardStop')) : null,
981
- h('button', { type: 'button', className: 'dpt-acard-btn', disabled: pending,
982
- onClick: () => { void run('dismiss'); } }, t('acardDismiss'))));
978
+ card.note ? h('p', { className: 'dpt-acard-note' }, card.note) : null,
979
+ h('div', { className: 'dpt-acard-actions' },
980
+ card.phase === 'open' && card.stop ? h('button', { type: 'button', className: 'dpt-acard-btn', disabled: pending, 'aria-busy': pending,
981
+ onClick: () => { void run(card.id, 'stop'); } }, card.stop.label ?? t('cardStopDefault')) : null,
982
+ h('button', { type: 'button', className: 'dpt-acard-btn', disabled: pending,
983
+ onClick: () => { void run(card.id, 'dismiss'); } }, t('cardDismiss'))),
984
+ done ? h('p', { className: 'dpt-acard-done', role: 'status' }, t(done)) : null);
985
+ }
986
+
987
+ function CardTail({ useProjection, run, t }) {
988
+ const state = useProjection('deepPtcCards');
989
+ const [busy, setBusy] = React.useState();
990
+ const cards = Array.isArray(state?.cards) ? state.cards : [];
991
+ if (cards.length === 0) return null;
992
+ async function act(id, action) {
993
+ setBusy(id);
994
+ try { await run(id, action); } catch { /* the projection is authoritative */ } finally { setBusy(undefined); }
995
+ }
996
+ return h('section', { className: 'dpt-cards', 'aria-label': t('cardLabel') },
997
+ ...cards.map(card => h(CardView, { key: card.id, card, run: act, pending: busy === card.id, t })));
983
998
  }
984
999
 
985
1000
  // ---------------------------------------------------------------------------------------------
@@ -1882,14 +1897,19 @@ ${ON}[data-dpt-busy] [data-dpt-send]::after{content:"";position:absolute;inset:-
1882
1897
  }, props => h(LocalizedSlot, { ...props, component: SkillCommandRow })));
1883
1898
  } catch { /* without the renderer the host shows its generic command row */ }
1884
1899
  try {
1885
- // Our own card kind gets its body; without it the host renders the fallback body, which keeps
1886
- // only the dismiss button. Optional: a host without action cards changes nothing else.
1887
- ctx.inject?.(['actionCards'], child => {
1888
- child.effect(() => child.actionCards.register({
1889
- action: 'deep-ptc-card', locale: 'deep-ptc', Body: props => h(ActionCardBody, props),
1890
- }), `${PLUGIN}: card body`);
1900
+ ctx.slots.inject('conversation.chat.commandview', () => ctx.slots.register({
1901
+ name: 'conversation.chat.commandview', key: CARD_COMMAND_NAME, locale: 'deep-ptc',
1902
+ }, props => h(LocalizedSlot, { ...props, component: CardCommandRow })));
1903
+ } catch { /* the host shows its generic command row */ }
1904
+ try {
1905
+ // Cards render at the end of the latest turn, in the page flow, never over the composer.
1906
+ ctx.inject?.(['remote', 'remote.commands'], child => {
1907
+ child.slots.inject('conversation.chat.turnTail', () => child.slots.register({
1908
+ name: 'conversation.chat.turnTail', id: 'deep-ptc-cards', order: 21, locale: 'deep-ptc',
1909
+ inject: sessionId => ({ run: (id, action) => runCardCommand(child, sessionId, { id, action }) }),
1910
+ }, props => h(LocalizedSlot, { ...props, component: CardTail })));
1891
1911
  });
1892
- } catch { /* the fallback body keeps the card usable */ }
1912
+ } catch { /* the conversation keeps working without the card */ }
1893
1913
  try {
1894
1914
  // Each conversation header reports which session is on screen and whether it works.
1895
1915
  ctx.slots.inject('conversation.session.header.actions', () => ctx.slots.register({
package/lib/index.mjs CHANGED
@@ -16,7 +16,7 @@ import { checkBeforeResolve } from './freshness.mjs';
16
16
  import { classifyDiagnosis } from './preset-health.mjs';
17
17
  import { applyActivity } from './session-activity.mjs';
18
18
  import { findSshClient, readSshHosts, sshGuidance } from './ssh.mjs';
19
- import { apply as applyActionCard } from './action-card-context.mjs';
19
+ import { apply as applyCards } from './cards-context.mjs';
20
20
  import { apply as applySkillContext } from './skill-context.mjs';
21
21
  import { applyRoot as applyToolStateRoot } from './tool-state.mjs';
22
22
 
@@ -205,9 +205,9 @@ export function apply(ctx, config) {
205
205
  void applySkillContext(ctx);
206
206
  // The tool state and its reset command follow the same rule, so the side card works in idle sessions too.
207
207
  void applyToolStateRoot(ctx);
208
- // One generic action card and its skill: the model can leave a small card under an answer.
209
- // Profile-level like the skill card, so an upgrade also reaches existing Deep PTC sessions.
210
- void applyActionCard(ctx);
208
+ // Conversation cards: a profile-level projection, command and tool, like the skill card, so a
209
+ // card works in any session and survives turns.
210
+ void applyCards(ctx);
211
211
  // Output files and SSH connections per conversation, for the side panel.
212
212
  void applyActivity(ctx);
213
213
  const lifecycle = presetLifecycle(
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-deep-ptc-mode",
3
- "version": "1.9.6",
3
+ "version": "1.9.7",
4
4
  "description": "Deep PTC for DeepSeek Harness: interruptible jobs, selectable shells, a side panel with clickable outputs and compact subagent rows, general SSH and DSH Go assistance, bilingual UI, and on-demand tools and skills for drawing, design and research.",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -1,89 +0,0 @@
1
- // Runtime for the Deep PTC action card.
2
- //
3
- // One generic kind, registered with the host's action-cards service, backs every
4
- // small card the user asks for. The card's one verb really runs here: it deletes
5
- // the scheduled tasks the card names and runs its command. The kind is optional:
6
- // a missing host service turns the card off instead of rejecting the preset.
7
-
8
- import { exec } from 'node:child_process';
9
- import { CARD_ACTION, CARD_INVITATION, CARD_SKILL, CARD_SKILL_REGISTRATION, CARD_STOP, cardDetails } from './action-card.mjs';
10
-
11
- export const name = 'deep-ptc-action-card';
12
- // Optional layer: a missing service disables the card rather than rejecting the preset.
13
- export const inject = [];
14
- const REQUIRED = ['actionCards', 'skills'];
15
- const STOP_TIMEOUT_MS = 30_000;
16
- const MAX_REASON = 300;
17
-
18
- const failure = reason => ({ status: 'refused', reason });
19
-
20
- export function apply(ctx) {
21
- // Starts once the host services exist; the caller never holds the boot for it.
22
- return ctx.plugin({ name: 'deep-ptc-action-card-layer', inject: REQUIRED, apply: install }).await()
23
- .catch(error => ctx.logger.warn('Deep PTC: action cards are off (%s)', error.message));
24
- }
25
-
26
- function install(ctx) {
27
- ctx.effect(() => ctx.actionCards.register({
28
- action: CARD_ACTION,
29
- skill: CARD_SKILL,
30
- invitation: CARD_INVITATION,
31
- details: cardDetails,
32
- // The one verb writes: a read-only sandbox refuses it before we run anything.
33
- verbs: { [CARD_STOP]: { writes: true } },
34
- statusFields: ['schedules', 'command', 'errors'],
35
- act: (agent, card, verb) => stop(ctx, agent, card, verb),
36
- }), 'Deep PTC: action card kind');
37
- ctx.effect(() => ctx.skills.register(CARD_SKILL_REGISTRATION), 'Deep PTC: action card skill');
38
- }
39
-
40
- /** Run the card's action, then record what really happened for the next model request. */
41
- async function stop(ctx, agent, card, verb) {
42
- if (verb !== CARD_STOP) return failure('unavailable');
43
- const stop = card.details.stop;
44
- if (stop === undefined) return failure('unavailable');
45
- const data = { schedules: [] };
46
- const errors = [];
47
- const schedule = stop.schedules === undefined ? undefined : ctx.get('schedule');
48
- for (const id of stop.schedules ?? []) {
49
- if (schedule === undefined) {
50
- errors.push('schedule service unavailable');
51
- break;
52
- }
53
- try {
54
- await schedule.edit({ id, action: 'delete' }, agent.id);
55
- data.schedules.push(id);
56
- } catch (error) {
57
- errors.push('schedule ' + id + ': ' + reason(error));
58
- ctx.logger.warn('Deep PTC: could not delete schedule %s (%s)', id, error.message);
59
- }
60
- }
61
- if (stop.command !== undefined) {
62
- try {
63
- await run(stop.command);
64
- data.command = 'ok';
65
- } catch (error) {
66
- data.command = 'failed';
67
- errors.push('command: ' + reason(error));
68
- ctx.logger.warn('Deep PTC: card command failed (%s)', error.message);
69
- }
70
- }
71
- if (errors.length > 0) data.errors = errors;
72
- const decision = { callId: card.callId, action: CARD_ACTION,
73
- phase: errors.length === 0 ? 'stopped' : 'failed', data };
74
- ctx.actionCards.record(agent, decision);
75
- return { status: 'settled', decision };
76
- }
77
-
78
- function reason(error) {
79
- return String(error?.message ?? error).trim().slice(0, MAX_REASON);
80
- }
81
-
82
- function run(command) {
83
- return new Promise((resolve, reject) => {
84
- exec(command, { timeout: STOP_TIMEOUT_MS, windowsHide: true, maxBuffer: 1 << 20 }, (error, _stdout, stderr) => {
85
- if (error === null) resolve();
86
- else reject(new Error(String(stderr ?? '').trim().split('\n')[0].slice(0, MAX_REASON) || error.message));
87
- });
88
- });
89
- }
@@ -1,156 +0,0 @@
1
- // Pure schema for the Deep PTC action card.
2
- //
3
- // One generic card kind backs every small card a user asks for: a title, a few
4
- // labelled rows, a note, and at most one verb that really stops what the card
5
- // describes. The host service validates `details` with `cardDetails`, and the
6
- // client body renders exactly these fields.
7
-
8
- export const CARD_ACTION = 'deep-ptc-card';
9
- export const CARD_SKILL = 'deep-ptc-cards';
10
- export const CARD_STOP = 'stop';
11
-
12
- const MAX_SUBTITLE = 120;
13
- const MAX_LABEL = 40;
14
- const MAX_VALUE = 300;
15
- const MAX_LINES = 12;
16
- const MAX_NOTE = 400;
17
- const MAX_STOP_LABEL = 24;
18
- const MAX_COMMAND = 2000;
19
- const MAX_SCHEDULES = 8;
20
- const MAX_SCHEDULE_ID = 120;
21
-
22
- const objects = value => value !== null && typeof value === 'object' && !Array.isArray(value);
23
- const text = (value, max) => typeof value === 'string' ? value.trim().slice(0, max) : '';
24
-
25
- function issue(path, message) {
26
- return { path, message };
27
- }
28
-
29
- function readLines(value, issues) {
30
- if (value === undefined) return [];
31
- if (!Array.isArray(value) || value.length > MAX_LINES) {
32
- issues.push(issue(['lines'], 'Use an array of at most ' + MAX_LINES + ' rows'));
33
- return [];
34
- }
35
- const rows = [];
36
- value.forEach((row, index) => {
37
- if (!objects(row)) {
38
- issues.push(issue(['lines', index], 'Each row is an object with label and value'));
39
- return;
40
- }
41
- const label = text(row.label, MAX_LABEL);
42
- const detail = text(row.value, MAX_VALUE);
43
- if (label === '') {
44
- issues.push(issue(['lines', index, 'label'], 'A row needs a label'));
45
- return;
46
- }
47
- rows.push({ label, value: detail });
48
- });
49
- return rows;
50
- }
51
-
52
- function readStop(value, issues) {
53
- if (value === undefined) return undefined;
54
- if (!objects(value)) {
55
- issues.push(issue(['stop'], 'stop must be an object'));
56
- return undefined;
57
- }
58
- const stop = {};
59
- const label = text(value.label, MAX_STOP_LABEL);
60
- if (label !== '') stop.label = label;
61
- const command = text(value.command, MAX_COMMAND);
62
- if (command !== '') stop.command = command;
63
- if (value.schedules !== undefined) {
64
- if (!Array.isArray(value.schedules) || value.schedules.length > MAX_SCHEDULES) {
65
- issues.push(issue(['stop', 'schedules'], 'Use at most ' + MAX_SCHEDULES + ' schedule ids'));
66
- } else {
67
- const ids = value.schedules.map(id => text(id, MAX_SCHEDULE_ID)).filter(id => id !== '');
68
- if (ids.length > 0) stop.schedules = ids;
69
- }
70
- }
71
- if (stop.command === undefined && stop.schedules === undefined) {
72
- issues.push(issue(['stop'], 'A stop action needs a command or schedule ids'));
73
- return undefined;
74
- }
75
- return stop;
76
- }
77
-
78
- /**
79
- * Normalize the `details` field of one card proposal.
80
- * @returns normalised card, or the list of problems for the model to fix.
81
- */
82
- export function parseCardDetails(value) {
83
- if (!objects(value)) return { issues: [issue(['details'], 'Use an object')] };
84
- const issues = [];
85
- const card = {};
86
- const subtitle = text(value.subtitle, MAX_SUBTITLE);
87
- if (subtitle !== '') card.subtitle = subtitle;
88
- const lines = readLines(value.lines, issues);
89
- if (lines.length > 0) card.lines = lines;
90
- const note = text(value.note, MAX_NOTE);
91
- if (note !== '') card.note = note;
92
- if (value.tone === 'warn') card.tone = 'warn';
93
- else if (value.tone !== undefined && value.tone !== 'info') issues.push(issue(['tone'], 'Use info or warn'));
94
- const stop = readStop(value.stop, issues);
95
- if (stop !== undefined) card.stop = stop;
96
- if (issues.length > 0) return { issues };
97
- if (card.subtitle === undefined && card.lines === undefined && card.note === undefined) {
98
- return { issues: [issue(['details'], 'A card needs a subtitle, lines or a note')] };
99
- }
100
- return { card };
101
- }
102
-
103
- /** The host service validates details through this `safeParse` contract. */
104
- export const cardDetails = {
105
- safeParse(value) {
106
- const parsed = parseCardDetails(value);
107
- if (parsed.card !== undefined) return { success: true, data: parsed.card };
108
- return { success: false, error: { issues: parsed.issues } };
109
- },
110
- };
111
-
112
- /** What the model is told after the card is admitted. */
113
- export const CARD_INVITATION = 'The user can run the card action or dismiss the card here; do not restate the card.';
114
-
115
- export const CARD_SKILL_DESCRIPTION = 'Place one small card under the answer (title, labelled rows, note) with an optional action the user can press.';
116
-
117
-
118
- export const CARD_SKILL_CONTENT = `# Small cards
119
-
120
- Use this skill when the user wants **a small card kept in the conversation**: a status card,
121
- a "should this loop continue" control card, a compact panel with one button. The card renders
122
- below your answer, never covers the composer, and its button really runs on the host.
123
-
124
- ## How to place one
125
-
126
- 1. Load this skill, then call \`propose_action\` once in the same turn:
127
- - \`action\`: always \`deep-ptc-card\`
128
- - \`title\`: short card title in the user's language
129
- - \`brief\`: one or two sentences on what this card is
130
- - \`details\`: the fields below
131
- 2. One card per turn. A second call in the same turn is refused; place a new card in a later turn.
132
- 3. After the call, do not restate the card's content in the answer.
133
-
134
- ## details
135
-
136
- - \`subtitle\` (optional): one small line under the title
137
- - \`lines\` (optional): up to 12 \`{ label, value }\` rows
138
- - \`note\` (optional): footnote, up to 400 characters
139
- - \`tone\` (optional): \`info\` or \`warn\`
140
- - \`stop\` (optional): the card's one action, shown as its button. Pressing it:
141
- - \`schedules\`: ids of scheduled tasks to delete (up to 8)
142
- - \`command\`: a command to run on the host (30 second timeout)
143
- - \`label\`: button text (optional, defaults to "停止")
144
-
145
- ## Rules
146
-
147
- - The action really runs. Say in \`brief\` what pressing it does.
148
- - Give \`stop\` only when the card needs a stop or tidy-up action; a purely
149
- informational card has just the dismiss button.
150
- - Keep the card short: it is a glanceable control, not a report.
151
- `;
152
-
153
- /** The registration the host skill service expects for this skill. */
154
- export const CARD_SKILL_REGISTRATION = {
155
- name: CARD_SKILL, description: CARD_SKILL_DESCRIPTION, content: CARD_SKILL_CONTENT, source: 'runtime',
156
- };