dsh-ptc-plus 0.5.1 → 0.5.2

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.
Files changed (58) hide show
  1. package/README.en.md +7 -3
  2. package/README.md +7 -3
  3. package/client.cjs +1467 -84
  4. package/compiler-core.cjs +132 -132
  5. package/compiler-core.cjs.map +3 -3
  6. package/docs/adr/0005-temporary-rejected-cell-edit-transport.md +2 -0
  7. package/docs/adr/0027-run-the-session-kernel-in-a-killable-helper-process.md +11 -1
  8. package/docs/adr/0032-own-session-log-facts-in-a-host-only-projection.md +31 -1
  9. package/docs/adr/0045-customize-model-visible-prompt-text.md +38 -0
  10. package/docs/adr/0046-gate-the-commit-with-the-semantic-evidence-tier.md +35 -0
  11. package/docs/adr/0047-store-journal-argument-digests-in-the-projection.md +88 -0
  12. package/docs/architecture.md +2 -2
  13. package/docs/client-ui.md +5 -2
  14. package/docs/durability-design.md +7 -1
  15. package/docs/releases/v0.5.2.md +79 -0
  16. package/docs/runtime-reference.md +36 -2
  17. package/docs/unmeasured-cell-recovery-repair-proposal.md +387 -0
  18. package/docs/verification.md +6 -2
  19. package/index.js +36 -15
  20. package/internal/bounded-literal.js +85 -0
  21. package/internal/capability-environment.js +162 -10
  22. package/internal/capability-plan.js +11 -8
  23. package/internal/cell-error.js +13 -0
  24. package/internal/config-spec.js +113 -2
  25. package/internal/direct-surface-owner.js +14 -10
  26. package/internal/edit-transport-owner.js +79 -14
  27. package/internal/isolated-worker.js +134 -17
  28. package/internal/kernel-worker.js +167 -3
  29. package/internal/legacy-cell-analysis.js +14 -2
  30. package/internal/legacy-repl-convenience.js +16 -3
  31. package/internal/projection-retention.js +238 -0
  32. package/internal/prompt-text.js +858 -0
  33. package/internal/recovery-tips.js +50 -11
  34. package/internal/rejected-cell-editor.js +3 -2
  35. package/internal/runtime-bridge-owner.js +1 -1
  36. package/internal/runtime-config.js +2 -0
  37. package/internal/runtime-contexts.js +14 -5
  38. package/internal/runtime-messages.js +43 -15
  39. package/internal/session-cell-executor.js +132 -11
  40. package/internal/session-journal-recovery.js +1009 -99
  41. package/internal/session-journal-schema.js +7 -5
  42. package/internal/session-journal.js +177 -14
  43. package/internal/session-log-view.js +111 -24
  44. package/internal/session-runtime.js +674 -33
  45. package/internal/session-state.js +27 -0
  46. package/internal/stateful-root-compiler.js +11 -0
  47. package/internal/stateful-root-runtime.js +17 -0
  48. package/internal/user-binding-console.js +7 -0
  49. package/internal/user-bindings-owner.js +3 -0
  50. package/internal/user-bindings.js +2 -2
  51. package/internal/validated-parse-repair.js +6 -1
  52. package/internal/worker-client.js +27 -4
  53. package/package.json +3 -1
  54. package/src/client-activity.js +24 -4
  55. package/src/client-capabilities-view.js +459 -24
  56. package/src/client-copy.js +163 -2
  57. package/src/client-repl-view.js +6 -1
  58. package/src/client-styles.js +64 -2
@@ -4,6 +4,10 @@ import { CAPABILITY_CONFIGURATION_KEYS, capabilityProfileConfiguration, validate
4
4
  import { readCapabilityCommandReceipt } from '../internal/capability-command-receipt.js'
5
5
  import { createFallbackModal } from './client-primitives.js'
6
6
  import { CAPABILITY_SORT_COLUMNS, capabilitySortDirection, cycleCapabilitySort, sortCapabilityEntries } from './client-capability-sort.js'
7
+ import {
8
+ PROMPT_ASSETS, PROMPT_TEXT_MAX_SLOT_BYTES, PROMPT_TEXT_SCHEMA,
9
+ accountPromptText, parsePromptTextDocument, resolvePromptText,
10
+ } from '../internal/prompt-text.js'
7
11
 
8
12
  export function capabilityCommandText(t, text) {
9
13
  if (text?.key) return t(text.key, text.params)
@@ -11,6 +15,20 @@ export function capabilityCommandText(t, text) {
11
15
  return receipt ? t(`capabilities.receipt.${receipt.state}`, { session: receipt.sessionId, error: receipt.error ?? '' }) : text
12
16
  }
13
17
 
18
+ // Host-owned context the model sees in PTC mode. The plugin never receives the host's
19
+ // own instruction text and cannot edit these bytes; it can only name the section it
20
+ // appends into or replaces. Listing them keeps the pane answering "what does the model
21
+ // actually see" instead of silently showing plugin-owned anchors only.
22
+ const HOST_CONTEXT_SECTIONS = Object.freeze([
23
+ Object.freeze({ id: 'host:system-prompt', presence: 'capabilities.prompt.hostPresenceEvery' }),
24
+ Object.freeze({ id: 'host:tools:sdk', presence: 'capabilities.prompt.hostPresenceCapabilities' }),
25
+ ])
26
+ // The prompt table is one column model shared by the colgroup, the header and every
27
+ // data row. Slot chips do not get a column: they render in their own full-width
28
+ // sub-row, because a narrow chip column stacked a five-slot anchor into a tall stack.
29
+ const PROMPT_TABLE_COLUMN_KEYS = Object.freeze(['channel', 'anchor', 'presence', 'bytes', 'reason', 'kind'])
30
+ const PROMPT_TABLE_COLUMNS = PROMPT_TABLE_COLUMN_KEYS.length
31
+
14
32
  function capabilityChoiceLabel(t, value) {
15
33
  return t(value === 'inherit' ? 'capabilities.quick.noOverride'
16
34
  : ['enabled', 'pending', 'unknown'].includes(value) ? `capabilities.quick.${value}`
@@ -30,13 +48,66 @@ function validCatalogRule(rule, temporary = false) {
30
48
  ? ['enabled', 'closed'].includes(choice) : CAPABILITY_DISCLOSURES.includes(choice))))
31
49
  }
32
50
 
51
+ /** A Chat snapshot without a node store cannot order a receipt against the conversation. */
52
+ const noSnapshot = () => undefined
53
+
54
+ /**
55
+ * The first human message is the conversation's opening position. DSH may reuse
56
+ * a blank Session, so capability commands recorded before that message are
57
+ * history from an earlier attempt, not part of this conversation; they must not
58
+ * appear above the user's first sentence.
59
+ */
60
+ export function firstHumanMessageSeq(nodes) {
61
+ if (nodes === null || nodes === undefined || typeof nodes.values !== 'function') return null
62
+ let first = null
63
+ for (const node of nodes.values()) {
64
+ if (node?.kind !== 'user' || node.data?.source?.kind !== 'user') continue
65
+ const seq = node.anchorSeq ?? node.data?.seq
66
+ if (!Number.isSafeInteger(seq)) continue
67
+ if (first === null || seq < first) first = seq
68
+ }
69
+ return first
70
+ }
71
+
72
+ /**
73
+ * A capability receipt belongs to chat only after the conversation has opened.
74
+ * A blank Session has nothing to announce, and a receipt recorded before the
75
+ * first human message describes a previous attempt's publication. A truncated
76
+ * Chat window cannot prove where the conversation opened, so its earliest
77
+ * loaded message must not hide a receipt the session may still own.
78
+ */
79
+ export function capabilityReceiptVisible(node, { blank = false, firstUserSeq = null, windowComplete = true } = {}) {
80
+ if (blank === true) return false
81
+ if (windowComplete !== true) return true
82
+ return !(Number.isSafeInteger(node?.seq) && Number.isSafeInteger(firstUserSeq) && node.seq < firstUserSeq)
83
+ }
84
+
33
85
  export function createCapabilityCommandCard(React) {
34
86
  const h = React.createElement
35
- return function CapabilityCommandCard({ node, t }) {
87
+ return function CapabilityCommandCard({ node, t, useChat, useSession }) {
36
88
  const [showSource, setShowSource] = React.useState(false)
89
+ // Both hooks are always called so the seat keeps one hook order whether or
90
+ // not the surrounding Chat or Session supplies its store.
91
+ const readSession = typeof useSession === 'function' ? useSession : noSnapshot
92
+ const blank = readSession(snapshot => snapshot?.blank === true) === true
93
+ // `hasMore` marks a window that does not reach the session start; only a
94
+ // complete window may claim its earliest human message is the first one.
95
+ const windowComplete = readSession(snapshot => snapshot?.hasMore !== true)
96
+ const readChat = typeof useChat === 'function' ? useChat : noSnapshot
97
+ const firstUserSeq = readChat(snapshot => firstHumanMessageSeq(snapshot?.nodes))
98
+ // A capability notice is the outcome of a `/capabilities` command the user
99
+ // submitted. What a new session publishes is a model-visible runtime context,
100
+ // not chat, so a node without that submitted input is not a user command and
101
+ // renders no notice: a fresh session has no change to announce.
102
+ if (typeof node.args !== 'string') return null
103
+ if (!capabilityReceiptVisible(node, { blank, firstUserSeq, windowComplete })) return null
37
104
  const command = `/${node.name ?? 'capabilities'}${node.args ? ` ${String(node.args).trim()}` : ''}`
38
105
  const text = node.outcome?.text
39
106
  const receipt = readCapabilityCommandReceipt(text)
107
+ // Pending is the plan's publication state, not an outcome: it becomes true
108
+ // only at the next accepted model step, so a durable notice would state a
109
+ // future that a historical row can no longer verify.
110
+ if (receipt?.state === 'pending') return null
40
111
  const legacyRefresh = text === 'Session capability environment refreshed; the model-visible notification is recorded.'
41
112
  if (receipt || String(node.args ?? '').trim() === 'refresh' || legacyRefresh) {
42
113
  const outcome = receipt ? t(`capabilities.card.${receipt.state}`, { error: receipt.error ?? '' })
@@ -128,12 +199,13 @@ export function capabilityPlanReason(t, entry) {
128
199
  export function createCapabilitySettingsViews(React, { SearchIcon, Select, Modal = createFallbackModal(React) }) {
129
200
  const h = React.createElement
130
201
  const field = key => CONFIG_FIELDS.find(item => item.key === key)
131
- const responsibilityGroups = [
132
- { tab: 'manual', keys: ['rules'] },
133
- { tab: 'budgets', keys: ['description', 'recovery', 'preview'] },
134
- { tab: 'statistics', keys: ['statistics'] },
135
- ]
136
- const responsibilities = responsibilityGroups.flatMap(group => group.keys)
202
+ // Each group owns one settings tab; the prompt text switch lives in the same
203
+ // capabilities section, so 新会话设置 must list it or a saved choice would be
204
+ // invisible there.
205
+ // 新会话设置 is one row of equally sized choices. Groups only existed to give each
206
+ // tab a caption; that produced a second row as soon as 提示文本 was added, so the
207
+ // choices stay flat and the navigation target is decided by `onNavigate` instead.
208
+ const responsibilities = ['rules', 'description', 'recovery', 'preview', 'statistics', 'promptText']
137
209
  const choicesFor = (configuration, plan) => {
138
210
  const historical = plan && ['ptc-capability-plan/v1', 'ptc-capability-plan/v3'].includes(plan.schema)
139
211
  && configuration && configuration.capabilityPolicy === undefined
@@ -143,10 +215,13 @@ export function createCapabilitySettingsViews(React, { SearchIcon, Select, Modal
143
215
  enabled: configuration?.capabilityManagementEnabled ?? plan?.enabled,
144
216
  statistics,
145
217
  recoveryEnabled: configuration?.capabilityRecoveryEnabled ?? (historical ? plan.enabled : undefined),
146
- previewEnabled: configuration?.modelPreviewEnabled ?? (historical ? plan.enabled : undefined) }
218
+ previewEnabled: configuration?.modelPreviewEnabled ?? (historical ? plan.enabled : undefined),
219
+ // The switch is new: a stored configuration without it means "on", the
220
+ // documented default, while an unreadable configuration stays unknown.
221
+ promptTextEnabled: configuration === undefined ? undefined : configuration.capabilityPromptTextEnabled !== false }
147
222
  }
148
223
  const flagsFor = settings => ({ rules: settings.enabled, description: settings.enabled, statistics: settings.statistics?.enabled,
149
- recovery: settings.recoveryEnabled, preview: settings.previewEnabled })
224
+ recovery: settings.recoveryEnabled, preview: settings.previewEnabled, promptText: settings.promptTextEnabled })
150
225
  const choiceState = (retained, applied, key) => typeof retained[key] !== 'boolean' ? 'unknown'
151
226
  : retained[key] ? typeof applied[key] !== 'boolean' ? 'unknown' : applied[key] === false ? 'paused' : 'selected'
152
227
  : key === 'rules' || key === 'description' ? 'host' : 'unselected'
@@ -176,17 +251,16 @@ export function createCapabilitySettingsViews(React, { SearchIcon, Select, Modal
176
251
  return h('section', { className: 'ptcPlusCombination', 'aria-label': t('capabilities.combination.saved') },
177
252
  h('div', { className: 'ptcPlusTaskHead' }, h('h4', null, t('capabilities.combination.saved')),
178
253
  h('span', { className: 'ptcPlusCapabilitySaveState', role: 'status' }, feedback)),
179
- h('div', { className: 'ptcPlusCombinationChoices' }, ...responsibilityGroups.map(group =>
180
- h('div', { key: group.tab, className: 'ptcPlusCombinationGroup', role: 'group',
181
- 'aria-label': t(`capabilities.tab.${group.tab}`) },
182
- h('strong', { className: 'ptcPlusCombinationGroupTitle' }, t(`capabilities.tab.${group.tab}`)),
183
- h('div', { className: 'ptcPlusCombinationGroupChoices' }, ...group.keys.map(key => {
184
- const state = choiceState(retained, applied, key)
185
- return h('button', { key, type: 'button', className: 'ptcPlusCombinationChoice', 'data-state': state,
186
- 'aria-controls': key === 'rules' || key === 'statistics' ? `${id}-pane-${group.tab}` : `${id}-context-pane-${key}`,
187
- onClick: () => onNavigate(key) }, h('span', null, t(`capabilities.combination.${key}`)),
188
- h('small', null, t(`capabilities.combination.state.${state}`)))
189
- }))))),
254
+ h('div', { className: 'ptcPlusCombinationChoices' }, ...responsibilities.map(key => {
255
+ const state = choiceState(retained, applied, key)
256
+ return h('button', { key, type: 'button', className: 'ptcPlusCombinationChoice', 'data-state': state,
257
+ 'data-choice': key,
258
+ 'aria-controls': key === 'promptText' ? `${id}-pane-prompt`
259
+ : key === 'rules' || key === 'statistics' ? `${id}-pane-${key === 'rules' ? 'manual' : 'statistics'}`
260
+ : `${id}-context-pane-${key}`,
261
+ onClick: () => onNavigate(key) }, h('span', null, t(`capabilities.combination.${key}`)),
262
+ h('small', null, t(`capabilities.combination.state.${state}`)))
263
+ })),
190
264
  h('p', { className: 'ptcPlusDetail', role: 'status' }, effect),
191
265
  h('details', { className: 'ptcPlusCapabilitySessionTools' }, h('summary', { tabIndex: 0 }, t('capabilities.existingSessions')),
192
266
  renderRefresh?.(),
@@ -889,17 +963,375 @@ export function createCapabilitySettingsViews(React, { SearchIcon, Select, Modal
889
963
  event.currentTarget.parentElement.querySelectorAll('[role=tab]')[next].focus({ preventScroll: true })
890
964
  }
891
965
 
966
+ /**
967
+ * Per-asset editor for the fixed prompt text the plugin writes.
968
+ *
969
+ * One row per registered asset: the built-in sentence stays visible as the
970
+ * placeholder, so a user compares against it instead of a blank box. The
971
+ * document is written through the normal settings path, which validates it;
972
+ * a document the panel cannot read is reported here instead of blanking the
973
+ * whole workbench.
974
+ */
975
+ // Registry codes are protocol identifiers. The pane shows a localized label and
976
+ // keeps the raw code in the element title, so a Chinese UI never reads like a
977
+ // dump of `fact-derived` / `protocol-exact-text` constants.
978
+ const PROMPT_REASON_KEYS = Object.freeze({
979
+ 'fact-derived': 'factDerived',
980
+ 'aggregate-frozen': 'aggregateFrozen',
981
+ 'protocol-exact-text': 'protocolExactText',
982
+ 'protocol-structural': 'protocolStructural',
983
+ 'shadows-host': 'shadowsHost',
984
+ 'other-owner': 'otherOwner',
985
+ })
986
+
987
+ function promptReasonLabel(t, reason) {
988
+ const key = PROMPT_REASON_KEYS[reason]
989
+ return key === undefined ? reason : t(`capabilities.prompt.reason.${key}`)
990
+ }
991
+
992
+ function promptKindLabel(t, kind) {
993
+ return kind === undefined ? '' : t(`capabilities.prompt.kind.${kind}`)
994
+ }
995
+
996
+ function PromptTextSettings({ value, disabled, onChange, t, id }) {
997
+ let document
998
+ let readError
999
+ try {
1000
+ document = parsePromptTextDocument(value.promptText)
1001
+ } catch (error) {
1002
+ readError = error.message
1003
+ document = { schema: PROMPT_TEXT_SCHEMA, overrides: {} }
1004
+ }
1005
+ // The workbench receives `disabled` as a per-field predicate, not a boolean.
1006
+ // The feature's own pause switch is separate from the settings lock: off means
1007
+ // every channel falls back to the built-in text while the saved document stays.
1008
+ const paused = value.capabilityPromptTextEnabled === false
1009
+ const blocked = paused || disabled === true
1010
+ || (typeof disabled === 'function' && disabled('promptText') === true)
1011
+ const resolved = resolvePromptText(value.promptText)
1012
+ const account = accountPromptText(resolved)
1013
+ // The pane stages edits in a draft and writes the document once, so the fields
1014
+ // and the preview always describe the same pending bytes. 保存 writes the draft;
1015
+ // 取消 drops it; a saved document still differs from the built-ins, so reopening
1016
+ // the pane shows that difference without a draft.
1017
+ const [draft, setDraft] = React.useState(null)
1018
+ const [selectedAnchorId, setSelectedAnchorId] = React.useState(null)
1019
+ const anchorPanelRef = React.useRef(null)
1020
+ const [openSlots, setOpenSlots] = React.useState({})
1021
+ const overrides = draft ?? document.overrides
1022
+ const byteCount = text => new TextEncoder().encode(text).length
1023
+ const group = number => String(Math.round(number)).replace(/\B(?=(\d{3})+(?!\d))/gu, ' ')
1024
+ const bytePair = bytes => t('capabilities.prompt.bytesPair', {
1025
+ bytes: group(bytes), kb: (bytes / 1024).toFixed(1),
1026
+ })
1027
+ const write = next => onChange(CONFIG_FIELDS.find(field => field.key === 'promptText'),
1028
+ JSON.stringify({ schema: PROMPT_TEXT_SCHEMA, overrides: next }))
1029
+ const update = (slotId, next) => {
1030
+ const base = { ...overrides }
1031
+ if (next === undefined) delete base[slotId]
1032
+ else base[slotId] = next
1033
+ setDraft(base)
1034
+ }
1035
+ const save = () => {
1036
+ if (draft === null) return
1037
+ write(draft)
1038
+ setDraft(null)
1039
+ }
1040
+ const cancel = () => setDraft(null)
1041
+ const pending = draft !== null
1042
+ const unmeasuredSlots = account.counts.unmeasuredSlots
1043
+ const dynamicSlots = account.counts.dynamicSlots
1044
+ const unwiredAnchors = account.anchors.filter(anchor => anchor.wired !== true)
1045
+ const measuredBytes = account.owners.A + account.owners.B + account.owners.C
1046
+ const ownerOf = anchor => (anchor.owner === 'mixed' ? 'mixed' : anchor.owner)
1047
+ const ownerAnchors = key => account.anchors.filter(anchor => ownerOf(anchor) === key).length
1048
+ // Icons are monochrome inline SVG: the mockup's cards carry a glyph, and an
1049
+ // icon font or an emoji would bring its own colour into the settings surface.
1050
+ const icon = path => h('svg', {
1051
+ viewBox: '0 0 20 20', width: 16, height: 16, fill: 'none', stroke: 'currentColor',
1052
+ 'stroke-width': 1.6, 'stroke-linecap': 'round', 'stroke-linejoin': 'round', 'aria-hidden': 'true',
1053
+ }, ...path.map((d, index) => h('path', { key: index, d })))
1054
+ const card = (key, labelKey, glyph) => {
1055
+ const mixed = key === 'mixed'
1056
+ const bytes = account.owners[key] ?? 0
1057
+ const value_ = mixed
1058
+ ? t('capabilities.prompt.cardMixed', { count: ownerAnchors('mixed') })
1059
+ : bytes > 0
1060
+ ? `${bytePair(bytes)} · ${t('capabilities.prompt.cardMetaAnchors', { count: ownerAnchors(key) })}`
1061
+ : t('capabilities.prompt.cardMetaAnchors', { count: ownerAnchors(key) })
1062
+ return h('div', { key, className: 'ptcPlusPromptCard', 'data-owner': key },
1063
+ h('span', { className: 'ptcPlusPromptCardIcon' }, glyph),
1064
+ h('span', { className: 'ptcPlusPromptCardBody' },
1065
+ h('span', { className: 'ptcPlusPromptCardLabel' }, t(labelKey)),
1066
+ mixed
1067
+ ? h('span', { className: 'ptcPlusPromptCardMeta' }, value_)
1068
+ : h('span', { className: 'ptcPlusPromptCardValue', 'data-owner-bytes': String(account.owners[key] ?? 0) }, value_)))
1069
+ }
1070
+ const cards = h('div', { className: 'ptcPlusPromptCards' },
1071
+ card('A', 'capabilities.prompt.ownerEditable', icon(['M4 16h3l9-9-3-3-9 9v3Z', 'M12.5 4.5 15.5 7.5'])),
1072
+ card('B', 'capabilities.prompt.ownerReadOnly', icon(['M5.5 9V6.5a4.5 4.5 0 0 1 9 0V9', 'M4.5 9h11v7h-11Z'])),
1073
+ card('C', 'capabilities.prompt.ownerOther', icon(['M10 10a3 3 0 1 0 0-6 3 3 0 0 0 0 6Z', 'M4 17c0-3 2.7-5 6-5s6 2 6 5'])),
1074
+ card('mixed', 'capabilities.prompt.ownerMixed', icon(['M4 6h12', 'M4 10h12', 'M4 14h12', 'M13 4v4', 'M7 8v4'])))
1075
+ const strip = h('p', { className: 'ptcPlusPromptStrip', 'data-prompt-strip': String(unwiredAnchors.length) },
1076
+ t('capabilities.prompt.strip', {
1077
+ anchors: unwiredAnchors.length, bytes: group(measuredBytes),
1078
+ kb: (measuredBytes / 1024).toFixed(1), total: account.counts.total,
1079
+ }))
1080
+ const reasonsOf = anchor => {
1081
+ const reasons = [...new Set(anchor.slots.map(slot => slot.reason).filter(Boolean))]
1082
+ return reasons.length === 0 ? '—' : reasons.map(reason => promptReasonLabel(t, reason)).join(' + ')
1083
+ }
1084
+ const kindsOf = anchor => [...new Set(anchor.slots.map(slot => slot.kind))]
1085
+ .map(kind => promptKindLabel(t, kind)).join(' + ')
1086
+ const splitOf = anchor => {
1087
+ const measured = anchor.slots.filter(slot => slot.measured === true && slot.bytes > 0)
1088
+ return measured.length > 1
1089
+ ? t('capabilities.prompt.anchorBytesSplit', {
1090
+ parts: measured.map(slot => `${slot.slotId.split('.').pop()} ${slot.bytes}`).join(' / '),
1091
+ })
1092
+ : null
1093
+ }
1094
+ const select = anchorId => setSelectedAnchorId(anchorId)
1095
+ // The expanded panel sits below the table, so on a short viewport selecting a
1096
+ // lower row would otherwise leave the editor it opened off-screen.
1097
+ React.useEffect(() => {
1098
+ if (selectedAnchorId === null) return
1099
+ const node = anchorPanelRef.current
1100
+ if (node === null || typeof node.scrollIntoView !== 'function') return
1101
+ node.scrollIntoView({ block: 'nearest', behavior: 'smooth' })
1102
+ }, [selectedAnchorId])
1103
+ const rowKey = (event, anchorId) => {
1104
+ if (event.key !== 'Enter' && event.key !== ' ') return
1105
+ event.preventDefault()
1106
+ select(anchorId)
1107
+ }
1108
+ const anchorRow = (anchor, index) => {
1109
+ const split = splitOf(anchor)
1110
+ return h('tr', {
1111
+ key: anchor.anchorId,
1112
+ className: 'ptcPlusPromptRow',
1113
+ 'data-anchor-id': anchor.anchorId,
1114
+ 'data-wired': anchor.wired === true ? 'true' : 'false',
1115
+ // A plain <table> row cannot carry aria-selected (that needs role="grid"),
1116
+ // so the expanded row is announced with aria-current instead.
1117
+ 'data-selected': selectedAnchorId === anchor.anchorId ? 'true' : 'false',
1118
+ 'aria-current': selectedAnchorId === anchor.anchorId ? 'true' : undefined,
1119
+ tabIndex: 0,
1120
+ onClick: () => select(anchor.anchorId),
1121
+ onKeyDown: event => rowKey(event, anchor.anchorId),
1122
+ },
1123
+ h('td', { className: 'ptcPlusPromptIndex' }, String(index)),
1124
+ h('td', null, h('span', { className: 'ptcPlusPromptChannel', 'data-channel': anchor.channel }, anchor.channel)),
1125
+ h('td', null, h('code', { className: 'ptcPlusPromptAnchorId', title: anchor.anchorId }, anchor.anchorId)),
1126
+ h('td', null, h('span', { className: 'ptcPlusPromptPresence', title: t(anchor.presence) }, t(anchor.presence))),
1127
+ h('td', { className: 'ptcPlusPromptBytesCell' },
1128
+ anchor.wired !== true
1129
+ ? h('span', { 'data-anchor-bytes': 'unwired' }, t('capabilities.prompt.unwiredRow', { slots: anchor.unmeasuredSlots }))
1130
+ : h('span', { 'data-anchor-bytes': String(anchor.bytes) },
1131
+ paused ? t('capabilities.prompt.pausedBytes', { bytes: anchor.bytes }) : t('capabilities.prompt.cardBytes', { bytes: anchor.bytes }),
1132
+ split === null ? null : h('small', { className: 'ptcPlusPromptSplit', 'data-anchor-split': 'true' }, split))),
1133
+ h('td', { className: 'ptcPlusPromptReasonCell' }, reasonsOf(anchor)),
1134
+ h('td', { className: 'ptcPlusPromptKindCell' }, kindsOf(anchor),
1135
+ anchor.wired !== true ? h('span', { className: 'ptcPlusPromptTag', 'data-prompt-unwired-tag': 'true' },
1136
+ t('capabilities.prompt.unwiredTag')) : null))
1137
+ }
1138
+ const hostRow = (section, index) => h('tr', {
1139
+ key: section.id, className: 'ptcPlusPromptRow ptcPlusPromptHostRow', 'data-host-row': section.id,
1140
+ },
1141
+ h('td', { className: 'ptcPlusPromptIndex' }, String(index)),
1142
+ h('td', null, h('span', { className: 'ptcPlusPromptChannel' }, 'prompt')),
1143
+ h('td', null, h('code', { className: 'ptcPlusPromptAnchorId', title: section.id }, section.id)),
1144
+ h('td', null, h('span', { className: 'ptcPlusPromptPresence' }, t(section.presence))),
1145
+ h('td', { className: 'ptcPlusPromptBytesCell' }, t('capabilities.prompt.hostUnavailable')),
1146
+ h('td', { className: 'ptcPlusPromptReasonCell' }, '—'),
1147
+ h('td', { className: 'ptcPlusPromptKindCell' }, t('capabilities.prompt.ownerHost')))
1148
+ const table = h('table', { className: 'ptcPlusPromptTable' },
1149
+ h('colgroup', null,
1150
+ h('col', { className: 'ptcPlusPromptColIndex' }),
1151
+ h('col', { className: 'ptcPlusPromptColChannel' }),
1152
+ h('col', { className: 'ptcPlusPromptColAnchor' }),
1153
+ h('col', { className: 'ptcPlusPromptColPresence' }),
1154
+ h('col', { className: 'ptcPlusPromptColBytes' }),
1155
+ h('col', { className: 'ptcPlusPromptColReason' }),
1156
+ h('col', { className: 'ptcPlusPromptColKind' })),
1157
+ h('thead', null, h('tr', null,
1158
+ h('th', { scope: 'col', className: 'ptcPlusPromptIndex' }, ''),
1159
+ h('th', { scope: 'col' }, t('capabilities.prompt.columnChannel')),
1160
+ h('th', { scope: 'col' }, t('capabilities.prompt.columnAnchor')),
1161
+ h('th', { scope: 'col' }, t('capabilities.prompt.columnPresence')),
1162
+ h('th', { scope: 'col' }, t('capabilities.prompt.columnBytesSplit')),
1163
+ h('th', { scope: 'col' }, t('capabilities.prompt.columnReason')),
1164
+ h('th', { scope: 'col' }, t('capabilities.prompt.columnKind')))),
1165
+ h('tbody', null,
1166
+ ...account.anchors.map((anchor, index) => anchorRow(anchor, index + 1)),
1167
+ ...HOST_CONTEXT_SECTIONS.map((section, index) => hostRow(section, account.anchors.length + index + 1))))
1168
+ const chip = (anchor, slot) => {
1169
+ const templateBytes = slot.measured === true && slot.kind === 'projected'
1170
+ const aggregateSet = slot.kind === 'aggregate'
1171
+ const shared = {
1172
+ className: 'ptcPlusPromptChip',
1173
+ 'data-slot-id': slot.slotId,
1174
+ 'data-slot-kind': slot.kind,
1175
+ ...(templateBytes ? { 'data-prompt-template-bytes': 'true' } : {}),
1176
+ ...(aggregateSet ? { 'data-prompt-aggregate-set': 'true' } : {}),
1177
+ title: templateBytes
1178
+ ? `${slot.slotId} · ${t('capabilities.prompt.templateBytes')}`
1179
+ : aggregateSet ? `${slot.slotId} · ${t('capabilities.prompt.aggregateFrozen')}` : slot.slotId,
1180
+ }
1181
+ if (slot.owner !== 'A') {
1182
+ return h('span', { key: slot.slotId, ...shared, 'data-readonly': 'true' },
1183
+ h('span', { className: 'ptcPlusPromptChipLabel' }, slot.slotId),
1184
+ h('span', { className: 'ptcPlusPromptChipNote' },
1185
+ t('capabilities.prompt.readonlyReason', { reason: promptReasonLabel(t, slot.reason), kind: promptKindLabel(t, slot.kind) })))
1186
+ }
1187
+ const selected = (openSlots[anchor.anchorId] ?? editableSlots(anchor)[0]?.slotId) === slot.slotId
1188
+ return h('button', {
1189
+ key: slot.slotId,
1190
+ ...shared,
1191
+ type: 'button',
1192
+ disabled: blocked,
1193
+ 'aria-pressed': selected,
1194
+ onClick: () => setOpenSlots(previous => ({ ...previous, [anchor.anchorId]: slot.slotId })),
1195
+ }, h('span', { className: 'ptcPlusPromptChipLabel' }, slot.slotId))
1196
+ }
1197
+ // One editor per anchor: the chips choose which editable slot is open, so the
1198
+ // run_code anchor keeps its three descriptions behind one field.
1199
+ const editableSlots = anchor => anchor.slots.filter(slot => slot.owner === 'A'
1200
+ && PROMPT_ASSETS.find(candidate => candidate.id === slot.slotId)?.defaultText !== null)
1201
+ const editorFor = anchor => {
1202
+ const slots = editableSlots(anchor)
1203
+ if (anchor.wired !== true || slots.length === 0) return null
1204
+ const selectedId = openSlots[anchor.anchorId] ?? slots[0].slotId
1205
+ const slot = slots.find(candidate => candidate.slotId === selectedId) ?? slots[0]
1206
+ const asset = PROMPT_ASSETS.find(candidate => candidate.id === slot.slotId)
1207
+ const override = Object.hasOwn(overrides, slot.slotId) ? overrides[slot.slotId] : undefined
1208
+ const current = override ?? asset.defaultText
1209
+ // The built-in sentence is the field's value, not a placeholder: the user must be
1210
+ // able to tweak the shipped wording without retyping it.
1211
+ return h('div', { key: slot.slotId, className: 'ptcPlusPromptEditor', 'data-editor-slot': slot.slotId },
1212
+ h('textarea', {
1213
+ id: `${id}-prompt-${slot.slotId}`, rows: 3, disabled: blocked, spellCheck: false,
1214
+ className: 'ptcPlusPromptTextarea', 'aria-label': slot.slotId, value: current,
1215
+ onChange: event => update(slot.slotId, event.target.value === '' ? undefined : event.target.value),
1216
+ }),
1217
+ h('div', { className: 'ptcPlusPromptEditorFoot' },
1218
+ h('span', { className: 'ptcPlusPromptHint' },
1219
+ t('capabilities.prompt.bytesOfLimit', { used: byteCount(current), max: PROMPT_TEXT_MAX_SLOT_BYTES })),
1220
+ h('span', { className: 'ptcPlusPromptEditorActions' },
1221
+ asset.omittable ? h('button', {
1222
+ type: 'button', className: 'ptcPlusButton', disabled: blocked,
1223
+ onClick: () => update(slot.slotId, ''),
1224
+ }, t('capabilities.prompt.omit')) : null,
1225
+ h('button', {
1226
+ type: 'button', className: 'ptcPlusButton', disabled: blocked || override === undefined,
1227
+ onClick: () => update(slot.slotId, undefined),
1228
+ }, t('capabilities.prompt.reset')))))
1229
+ }
1230
+ const defaultAnchor = account.anchors.find(anchor => anchor.wired === true && editableSlots(anchor).length > 0)
1231
+ const selectedAnchor = account.anchors.find(anchor => anchor.anchorId === selectedAnchorId) ?? defaultAnchor
1232
+ const selectedIndex = selectedAnchor === undefined ? 0 : account.anchors.indexOf(selectedAnchor) + 1
1233
+ const anchorPanel = h('section', { className: 'ptcPlusPromptPanel', 'data-prompt-panel': 'anchor', ref: anchorPanelRef },
1234
+ h('h5', { className: 'ptcPlusPromptPanelTitle' },
1235
+ t('capabilities.prompt.rowExpand', { index: selectedIndex })),
1236
+ selectedAnchor === undefined
1237
+ ? h('p', { className: 'ptcPlusPromptHint' }, t('capabilities.prompt.rowExpandHint'))
1238
+ : h('div', { className: 'ptcPlusPromptPanelBody' },
1239
+ h('div', { className: 'ptcPlusPromptChips', 'data-anchor-chips': selectedAnchor.anchorId },
1240
+ ...selectedAnchor.slots.map(slot => chip(selectedAnchor, slot))),
1241
+ selectedAnchor.wired !== true
1242
+ ? h('p', { className: 'ptcPlusPromptHint' }, t('capabilities.prompt.unwiredRow', { slots: selectedAnchor.unmeasuredSlots }))
1243
+ : editorFor(selectedAnchor)))
1244
+ // Saving shows what will change. The preview is derived from the same draft the
1245
+ // editors write, so it cannot disagree with them; a saved document that already
1246
+ // differs from the built-ins shows here too, because saving would rewrite it.
1247
+ const changes = account.anchors.flatMap(anchor => anchor.slots
1248
+ .map(slot => ({ slot, builtin: PROMPT_ASSETS.find(asset => asset.id === slot.slotId)?.defaultText }))
1249
+ .filter(entry => typeof entry.builtin === 'string'
1250
+ && Object.hasOwn(overrides, entry.slot.slotId)
1251
+ && overrides[entry.slot.slotId] !== entry.builtin)
1252
+ .map(entry => {
1253
+ const effective = overrides[entry.slot.slotId]
1254
+ const effect = anchor.channel === 'plan' ? t('capabilities.prompt.effectPlan')
1255
+ : anchor.channel === 'install' ? t('capabilities.prompt.effectInstall')
1256
+ : anchor.channel === 'prompt' ? t('capabilities.prompt.effectPrompt')
1257
+ : t('capabilities.prompt.effectTrigger')
1258
+ return {
1259
+ anchor, slot: entry.slot, effect,
1260
+ before: byteCount(entry.builtin), after: byteCount(effective), delta: byteCount(effective) - byteCount(entry.builtin),
1261
+ }
1262
+ }))
1263
+ const restoreSlot = slotId => update(slotId, undefined)
1264
+ const diffPanel = h('section', {
1265
+ className: 'ptcPlusPromptPanel',
1266
+ ...(changes.length === 0 ? {} : { 'data-prompt-diff': 'true' }),
1267
+ 'data-prompt-diff-panel': 'true',
1268
+ },
1269
+ h('h5', { className: 'ptcPlusPromptPanelTitle' }, t('capabilities.prompt.diffTitle')),
1270
+ changes.length === 0
1271
+ ? h('p', { className: 'ptcPlusPromptHint' }, t('capabilities.prompt.diffEmpty'))
1272
+ : h('ul', { className: 'ptcPlusPromptDiffList' },
1273
+ ...changes.map((entry, index) => h('li', {
1274
+ key: entry.slot.slotId, className: 'ptcPlusPromptDiffRow',
1275
+ 'data-diff-anchor': entry.anchor.anchorId, 'data-diff-slot': entry.slot.slotId,
1276
+ },
1277
+ h('span', { className: 'ptcPlusPromptDot', 'data-tone': String(index % 3) }),
1278
+ h('span', { className: 'ptcPlusPromptDiffBody' },
1279
+ h('span', { className: 'ptcPlusPromptDiffHead' },
1280
+ h('code', { className: 'ptcPlusPromptDiffSlot' }, entry.slot.slotId),
1281
+ h('span', { className: 'ptcPlusPromptHint' }, entry.effect)),
1282
+ h('span', { className: 'ptcPlusPromptDiffDelta' },
1283
+ t('capabilities.prompt.diffBytes', {
1284
+ before: group(entry.before), after: group(entry.after),
1285
+ delta: entry.delta > 0 ? `+${group(entry.delta)}` : group(entry.delta),
1286
+ }),
1287
+ h('button', {
1288
+ type: 'button', className: 'ptcPlusButton', disabled: blocked,
1289
+ onClick: () => restoreSlot(entry.slot.slotId),
1290
+ }, t('capabilities.prompt.reset'))))))),
1291
+ h('div', { className: 'ptcPlusPromptActions' },
1292
+ h('button', {
1293
+ type: 'button', className: 'ptcPlusButton', 'data-kind': 'primary', disabled: blocked || !pending,
1294
+ onClick: save,
1295
+ }, t('capabilities.prompt.save')),
1296
+ h('button', { type: 'button', className: 'ptcPlusButton', disabled: blocked || !pending, onClick: cancel },
1297
+ t('capabilities.prompt.cancel'))))
1298
+ return h('section', {
1299
+ className: 'ptcPlusPromptText', 'data-prompt-paused': paused ? 'true' : 'false',
1300
+ },
1301
+ h('header', { className: 'ptcPlusPromptHeader' },
1302
+ h('span', { className: 'ptcPlusPromptHeaderIcon' }, icon(['M10 2.5 12 8l5.5 2-5.5 2-2 5.5-2-5.5L2.5 10 8 8Z'])),
1303
+ h('span', { className: 'ptcPlusPromptHeaderBody' },
1304
+ h('h4', { className: 'ptcPlusPromptTitle' }, t('capabilities.prompt.title')),
1305
+ h('p', { className: 'ptcPlusPromptSubtitle' }, t('capabilities.prompt.subtitle')))),
1306
+ paused
1307
+ ? h('p', { className: 'ptcPlusPromptPaused', role: 'status', 'data-prompt-paused-notice': 'true' },
1308
+ t('capabilities.prompt.paused'))
1309
+ : null,
1310
+ readError === undefined ? null : h('p', { className: 'ptcPlusPromptHint' }, t('capabilities.prompt.unreadable', { error: readError })),
1311
+ ...resolved.reported.map((entry, index) => h('p', { key: `report-${index}`, className: 'ptcPlusPromptHint' },
1312
+ t('capabilities.prompt.reported', {
1313
+ asset: entry.slotId ?? entry.anchorId ?? 'document', reason: entry.reason,
1314
+ }))),
1315
+ cards,
1316
+ strip,
1317
+ h('p', { className: 'ptcPlusPromptHint', 'data-prompt-slot-counts': 'true' },
1318
+ t('capabilities.prompt.slotCounts', { bytes: group(measuredBytes), unmeasured: unmeasuredSlots, dynamic: dynamicSlots })),
1319
+ table,
1320
+ h('div', { className: 'ptcPlusPromptPanels' }, anchorPanel, diffPanel),
1321
+ h('p', { className: 'ptcPlusPromptIntro' }, t('capabilities.prompt.intro')))
1322
+ }
1323
+
892
1324
  function CapabilityWorkbench({ value, configurationReady, catalog, catalogError, plans, plansError, plansPending, plansStale, disabled, onChange, onReload, t, renderField, renderPlans, renderRefresh, id, selectedSessionId, onSessionSelect,
893
1325
  allocation, allocationError, allocationPending, onApplyConfiguration, configurationWritable, saving, saveStatus }) {
894
1326
  const [tab, setTab] = React.useState('manual')
895
1327
  const [contextSection, setContextSection] = React.useState('description')
896
- const tabs = ['manual', 'budgets', 'statistics', 'plans']
1328
+ const tabs = ['manual', 'budgets', 'statistics', 'prompt', 'plans']
897
1329
  const feedback = saving ? t('state.syncing') : saveStatus && saveStatus.key !== 'status.applied' ? t(saveStatus.key, saveStatus.params)
898
1330
  : t(configurationWritable ? 'capabilities.savedForNew' : 'footer.readOnly')
899
1331
  return h('div', { className: 'ptcPlusCapabilityWorkbench' },
900
1332
  h(CombinationSummary, { value, configurationReady, plans, plansError, plansPending, plansStale, selectedSessionId,
901
1333
  feedback, onReload, renderRefresh, renderPlans, t, id, onNavigate: key => {
902
- setTab(key === 'rules' ? 'manual' : key === 'statistics' ? 'statistics' : 'budgets')
1334
+ setTab(key === 'rules' ? 'manual' : key === 'statistics' ? 'statistics' : key === 'promptText' ? 'prompt' : 'budgets')
903
1335
  if (['description', 'recovery', 'preview'].includes(key)) setContextSection(key)
904
1336
  } }),
905
1337
  h('div', { className: 'ptcPlusCapabilityTabs', role: 'tablist', 'aria-label': t('capabilities.settingsTabs') },
@@ -909,7 +1341,7 @@ export function createCapabilitySettingsViews(React, { SearchIcon, Select, Modal
909
1341
  }, t(`capabilities.tab.${key}`)))),
910
1342
  ...tabs.map(key => h('div', { key, className: 'ptcPlusCapabilityPane', role: 'tabpanel', id: `${id}-pane-${key}`,
911
1343
  'aria-labelledby': `${id}-tab-${key}`, hidden: tab !== key },
912
- h('div', { className: 'ptcPlusTaskHead' }, h('h4', null, t(`capabilities.title.${key}`)),
1344
+ key === 'prompt' ? null : h('div', { className: 'ptcPlusTaskHead' }, h('h4', null, t(`capabilities.title.${key}`)),
913
1345
  key === 'manual' ? h('label', { className: 'ptcPlusCapabilityManagement' }, h('span', null, t('capabilities.management')),
914
1346
  h('input', { type: 'checkbox', role: 'switch', className: 'ptcPlusCheck', checked: value.capabilityManagementEnabled === true,
915
1347
  disabled: disabled('capabilityManagementEnabled'), 'aria-label': t('capabilities.management'),
@@ -926,7 +1358,10 @@ export function createCapabilitySettingsViews(React, { SearchIcon, Select, Modal
926
1358
  h(AllocationEvidence, { allocation, allocationError, allocationPending, selectedSessionId, statistics: true, onReload, t }))
927
1359
  : key === 'budgets' ? h(ContextSettings, { value, configurationReady, disabled, onChange, t, renderField, allocation, allocationError, allocationPending,
928
1360
  selectedSessionId, onReload, renderRefresh, id, section: contextSection, setSection: setContextSection })
929
- : h(ConfigurationProfiles, { value, plans, disabled, writable: configurationWritable, onChange, onApplyConfiguration, t }))))
1361
+ // Rendered only while its tab is active: eight idle textareas in a hidden
1362
+ // pane would change every generic textbox query in the settings card.
1363
+ : key === 'prompt' ? (tab === 'prompt' ? h(PromptTextSettings, { value, disabled, onChange, t, id }) : null)
1364
+ : h(ConfigurationProfiles, { value, plans, disabled, writable: configurationWritable, onChange, onApplyConfiguration, t }))))
930
1365
  }
931
1366
 
932
1367
  return { CapabilityWorkbench }