@shuind/dsh-codex-harness 0.2.21 → 0.2.32-dsh-v0.2.2-rc.1
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 +121 -0
- package/README.md +48 -38
- package/RELEASE.md +61 -0
- package/assets/codex.svg +5 -0
- package/cordis.patch.yml +150 -6
- package/docs/preset-library.md +39 -23
- package/docs/tool-policy-benchmark.json +310 -0
- package/docs/tool-policy.md +144 -0
- package/lib/client.js +1639 -111
- package/lib/compaction.js +17 -2
- package/lib/index.js +799 -188
- package/lib/installer.js +50 -6
- package/lib/preferences.js +111 -0
- package/lib/tool-policy.js +2235 -0
- package/lib/typert.js +57 -10
- package/lib/types/activity.d.ts +1 -1
- package/lib/types/activity.js +50 -14
- package/lib/types/client/activity.d.ts +33 -9
- package/lib/types/client/desktop.d.ts +43 -0
- package/lib/types/client/desktop.js +121 -0
- package/lib/types/client/entry.d.ts +10 -0
- package/lib/types/client/entry.js +12 -0
- package/lib/types/client/index.d.ts +109 -19
- package/lib/types/client/index.js +21 -40
- package/lib/types/client/policy-drafts.d.ts +25 -0
- package/lib/types/client/policy-drafts.js +47 -0
- package/lib/types/client/preset-copy.d.ts +1 -0
- package/lib/types/client/preset-copy.js +2 -0
- package/lib/types/client/preset-manager.d.ts +12 -2
- package/lib/types/client/preset-manager.js +70 -25
- package/lib/types/client/preset-requests.d.ts +12 -0
- package/lib/types/client/preset-requests.js +101 -0
- package/lib/types/client/session.d.ts +6 -0
- package/lib/types/client/session.js +9 -0
- package/lib/types/client/tool-policy.d.ts +120 -0
- package/lib/types/client/tool-policy.js +394 -0
- package/lib/types/compaction.d.ts +3 -3
- package/lib/types/compaction.js +6 -2
- package/lib/types/desktop-preset.d.ts +20 -0
- package/lib/types/desktop-preset.js +39 -0
- package/lib/types/exec.d.ts +4 -0
- package/lib/types/exec.js +192 -66
- package/lib/types/host-settings.d.ts +4 -0
- package/lib/types/host-settings.js +13 -0
- package/lib/types/index.d.ts +20 -2
- package/lib/types/index.js +181 -68
- package/lib/types/installer.js +11 -2
- package/lib/types/preferences.d.ts +11 -0
- package/lib/types/preferences.js +16 -0
- package/lib/types/preset-editor-remote.d.ts +2 -0
- package/lib/types/preset-editor-remote.js +6 -2
- package/lib/types/preset-editor.d.ts +12 -7
- package/lib/types/preset-editor.js +43 -13
- package/lib/types/preset-prompt-catalog-schema.d.ts +16 -0
- package/lib/types/preset-prompt-catalog-schema.js +11 -0
- package/lib/types/preset-prompt-catalog.d.ts +21 -0
- package/lib/types/preset-prompt-catalog.js +192 -0
- package/lib/types/preset-prompt-contract.d.ts +22 -0
- package/lib/types/preset-prompt-contract.js +3 -0
- package/lib/types/preset-tool-catalog-schema.d.ts +38 -0
- package/lib/types/preset-tool-catalog-schema.js +28 -0
- package/lib/types/preset-tool-catalog.d.ts +5 -0
- package/lib/types/preset-tool-catalog.js +51 -0
- package/lib/types/prompt-sections.d.ts +1 -1
- package/lib/types/prompt-sections.js +9 -3
- package/lib/types/prompt.js +4 -2
- package/lib/types/remote.js +23 -8
- package/lib/types/settings.d.ts +3 -3
- package/lib/types/settings.js +3 -3
- package/lib/types/tool-capabilities.d.ts +32 -0
- package/lib/types/tool-capabilities.js +42 -0
- package/lib/types/tool-policy-contract.d.ts +60 -0
- package/lib/types/tool-policy-contract.js +26 -0
- package/lib/types/tool-policy.d.ts +171 -0
- package/lib/types/tool-policy.js +367 -0
- package/lib/types/typert.host.d.ts +2 -2
- package/lib/types/typert.host.js +12 -2
- package/locale/en.json +6 -0
- package/locale/tool-policy/en.json +6 -0
- package/locale/tool-policy/zh.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +375 -299
- package/scripts/benchmark-tool-policy.mjs +186 -0
- package/scripts/build-preset.mjs +19 -0
- package/scripts/clean-build.mjs +11 -0
- package/src/activity-types.ts +7 -0
- package/src/activity.ts +158 -0
- package/src/client/activity.ts +82 -0
- package/src/client/desktop.tsx +162 -0
- package/src/client/entry.tsx +16 -0
- package/src/client/index.tsx +972 -0
- package/src/client/policy-drafts.ts +56 -0
- package/src/client/preset-copy.ts +83 -0
- package/src/client/preset-manager.tsx +281 -0
- package/src/client/preset-requests.ts +113 -0
- package/src/client/session.ts +11 -0
- package/src/client/tool-policy.tsx +380 -0
- package/src/compact-command.ts +112 -0
- package/src/compaction.ts +190 -0
- package/src/context.ts +15 -0
- package/src/desktop-preset.ts +55 -0
- package/src/exec.ts +570 -0
- package/src/host-settings.ts +17 -0
- package/src/index.ts +1097 -0
- package/src/installer.ts +172 -0
- package/src/invariant.ts +34 -0
- package/src/patch.ts +258 -0
- package/src/preferences.ts +17 -0
- package/src/preset-contract.ts +85 -0
- package/src/preset-editor-remote.ts +41 -0
- package/src/preset-editor.ts +502 -0
- package/src/preset-prompt-catalog-schema.ts +10 -0
- package/src/preset-prompt-catalog.ts +191 -0
- package/src/preset-prompt-contract.ts +21 -0
- package/src/preset-tool-catalog-schema.ts +28 -0
- package/src/preset-tool-catalog.ts +51 -0
- package/src/prompt-sections.ts +33 -0
- package/src/prompt.ts +62 -0
- package/src/remote.ts +748 -0
- package/src/settings.ts +79 -0
- package/src/tool-capabilities.ts +76 -0
- package/src/tool-policy-contract.ts +76 -0
- package/src/tool-policy.ts +388 -0
- package/src/typert.host.ts +119 -0
- package/tsconfig.json +29 -0
- package/tsdown.config.ts +110 -0
- package/lib/types/preset-templates.d.ts +0 -36
- package/lib/types/preset-templates.js +0 -12
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import type { ToolPolicyRule } from '../tool-policy-contract.ts'
|
|
2
|
+
|
|
3
|
+
/** Ephemeral UI drafts only; accepted ConfigForms values remain authoritative. */
|
|
4
|
+
export interface PresetDraft {
|
|
5
|
+
readonly preset: string
|
|
6
|
+
readonly revision: number | undefined
|
|
7
|
+
readonly baseline: readonly ToolPolicyRule[]
|
|
8
|
+
readonly rules: readonly ToolPolicyRule[]
|
|
9
|
+
}
|
|
10
|
+
export type PresetDrafts = ReadonlyMap<string, PresetDraft>
|
|
11
|
+
export interface PolicySnapshot { readonly revision: number | undefined; readonly rules: readonly ToolPolicyRule[] }
|
|
12
|
+
export interface PreparedPresetSave extends PolicySnapshot { readonly draft: PresetDraft; readonly before: PolicySnapshot }
|
|
13
|
+
|
|
14
|
+
function canonical(value: unknown): unknown {
|
|
15
|
+
if (Array.isArray(value)) return value.map(canonical)
|
|
16
|
+
if (value !== null && typeof value === 'object') return Object.fromEntries(Object.entries(value)
|
|
17
|
+
.filter(([, item]) => item !== undefined).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, canonical(item)]))
|
|
18
|
+
return value
|
|
19
|
+
}
|
|
20
|
+
export const sameRules = (a: readonly ToolPolicyRule[], b: readonly ToolPolicyRule[]): boolean => JSON.stringify(canonical(a)) === JSON.stringify(canonical(b))
|
|
21
|
+
export const presetRules = (rules: readonly ToolPolicyRule[], preset: string): readonly ToolPolicyRule[] => rules.filter(rule => rule.preset === preset)
|
|
22
|
+
|
|
23
|
+
export function editPresetDraft(drafts: PresetDrafts, preset: string, accepted: PolicySnapshot,
|
|
24
|
+
change: (rules: readonly ToolPolicyRule[]) => readonly ToolPolicyRule[]): PresetDrafts {
|
|
25
|
+
const previous = drafts.get(preset)
|
|
26
|
+
const next = new Map(drafts)
|
|
27
|
+
next.set(preset, { preset, revision: previous === undefined ? accepted.revision : previous.revision,
|
|
28
|
+
baseline: previous?.baseline ?? accepted.rules, rules: change(previous?.rules ?? presetRules(accepted.rules, preset)) })
|
|
29
|
+
return next
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Replace just this source target, preserving all accepted other targets/order. */
|
|
33
|
+
export function mergePresetRules(accepted: readonly ToolPolicyRule[], preset: string, replacement: readonly ToolPolicyRule[]): readonly ToolPolicyRule[] {
|
|
34
|
+
const first = accepted.findIndex(rule => rule.preset === preset)
|
|
35
|
+
if (first < 0) return [...accepted, ...replacement]
|
|
36
|
+
return [...accepted.slice(0, first), ...replacement, ...accepted.slice(first).filter(rule => rule.preset !== preset)]
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function preparePresetSave(draft: PresetDraft, accepted: PolicySnapshot): PreparedPresetSave {
|
|
40
|
+
// Never silently rebase an external edit, even if only a different target changed.
|
|
41
|
+
if (draft.revision !== accepted.revision || !sameRules(draft.baseline, accepted.rules)) throw new Error('policy-draft-conflict')
|
|
42
|
+
return { draft, before: accepted, revision: draft.revision, rules: mergePresetRules(accepted.rules, draft.preset, draft.rules) }
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function acceptPresetSave(drafts: PresetDrafts, saved: PreparedPresetSave, accepted: PolicySnapshot): PresetDrafts {
|
|
46
|
+
const next = new Map(drafts)
|
|
47
|
+
if (next.get(saved.draft.preset) === saved.draft) next.delete(saved.draft.preset)
|
|
48
|
+
// A true result is not enough: a later external view may already have arrived.
|
|
49
|
+
if (!sameRules(accepted.rules, saved.rules)) return next
|
|
50
|
+
for (const [preset, draft] of next) {
|
|
51
|
+
if (draft.revision !== saved.before.revision || !sameRules(draft.baseline, saved.before.rules)) continue
|
|
52
|
+
if (!sameRules(presetRules(saved.before.rules, preset), presetRules(accepted.rules, preset))) continue
|
|
53
|
+
next.set(preset, { ...draft, revision: accepted.revision, baseline: accepted.rules })
|
|
54
|
+
}
|
|
55
|
+
return next
|
|
56
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
export const presetEn = {
|
|
2
|
+
pmRegistryReadOnly: 'This host exposes read-only preset declarations. Edit global Codex settings below; creating editable preset copies is not supported here.',
|
|
3
|
+
peConnectionError: 'Could not connect to the local service. Retry loading; if the connection still fails, reconnect the page.',
|
|
4
|
+
peReadError: 'Could not read this preset. Retry loading or refresh the preset list.',
|
|
5
|
+
peRetryRead: 'Retry loading',
|
|
6
|
+
peReconnect: 'Reconnect page',
|
|
7
|
+
peSystemPrompt: 'System prompt sections',
|
|
8
|
+
peSectionsHint: 'These templates contribute to this preset’s system prompt before the tools. Runtime variables, workspace instructions and plugin-provided guidance are assembled when the conversation runs.',
|
|
9
|
+
peDynamicPrompt: 'This field is an expression; it is preserved without executing it in the editor.',
|
|
10
|
+
peDshSourcePrompt: 'Tells the agent where the DSH source checkout is and keeps it separate from the current workspace. It is used when inspecting or extending DSH itself.',
|
|
11
|
+
peDshWebPrompt: 'Tells the agent which Web page it is talking through, what “this page” means, and when Web changes need a rebuild or refresh.',
|
|
12
|
+
peSuppressed: 'Not used',
|
|
13
|
+
peCompletePersona: 'This preset uses Persona as its entire system prompt, so this section is excluded.',
|
|
14
|
+
peLoading: 'Reading preset…',
|
|
15
|
+
peTitle: 'Preset editor',
|
|
16
|
+
peHierarchy: 'Codex mode and other presets are peers. Choose one to edit, or make an editable copy of a built-in preset first.',
|
|
17
|
+
peSelect: 'Preset',
|
|
18
|
+
peSelectPlaceholder: 'Choose a preset…',
|
|
19
|
+
peEditable: 'This is an editable user preset.',
|
|
20
|
+
peBuiltinEdit: 'Built-in presets are read-only. Create a copy to edit it.',
|
|
21
|
+
peCreateCopy: 'Create editable copy',
|
|
22
|
+
peCodexSection: 'Codex mode capabilities',
|
|
23
|
+
peAddCodex: 'Add Codex capabilities to this preset',
|
|
24
|
+
peAddCodexHint: 'Adds the Codex prompt, tools, hosted search, and remote compaction to this preset.',
|
|
25
|
+
peActivityGlobal: 'Activity status is a global display setting and is shared by all presets.',
|
|
26
|
+
peSaveCopy: 'Save new preset',
|
|
27
|
+
peSaved: 'Saved. Select this preset in a new conversation.',
|
|
28
|
+
pmGlobalSettings: 'Global settings',
|
|
29
|
+
pmRefresh: 'Refresh',
|
|
30
|
+
pmBuiltIn: 'Built-in',
|
|
31
|
+
pmCustom: 'Custom',
|
|
32
|
+
pmDiscard: 'Discard your unsaved changes?',
|
|
33
|
+
pmConflict: 'This preset changed in another page or on disk. Reopen the latest version before saving.',
|
|
34
|
+
pmYamlError: 'The configuration must be valid YAML. Your draft has not been saved.',
|
|
35
|
+
pmErrorDetails: 'Technical details',
|
|
36
|
+
pmSaveError: 'Could not complete this action. Your draft is still here.',
|
|
37
|
+
pmName: 'Name',
|
|
38
|
+
pmDescription: 'Description',
|
|
39
|
+
pmCancel: 'Cancel',
|
|
40
|
+
pmSave: 'Save changes',
|
|
41
|
+
} as const
|
|
42
|
+
|
|
43
|
+
export const presetZh: Record<keyof typeof presetEn, string> = {
|
|
44
|
+
pmRegistryReadOnly: 'This host exposes read-only preset declarations. Edit global Codex settings below; creating editable preset copies is not supported here.',
|
|
45
|
+
peConnectionError: '未能连接本地服务。请重试读取;如果仍然失败,请重新连接页面。',
|
|
46
|
+
peReadError: '无法读取这个预设,请重试读取或刷新预设列表。',
|
|
47
|
+
peRetryRead: '重试读取',
|
|
48
|
+
peReconnect: '重新连接页面',
|
|
49
|
+
peSystemPrompt: '系统提示词',
|
|
50
|
+
peSectionsHint: '这些模板共同组成当前预设在工具之前的系统提示词。运行时变量、工作区指令和插件提供的说明会在会话中组装。',
|
|
51
|
+
peDynamicPrompt: '此字段是动态表达式,编辑器保留原值,不执行表达式。',
|
|
52
|
+
peDshSourcePrompt: '告诉 Agent DSH 源码检出目录在哪里,并与当前工作区区分开;用于检查或扩展 DSH 本身。',
|
|
53
|
+
peDshWebPrompt: '告诉 Agent 当前通过哪个 Web 页面交互、“这个页面”指什么,以及 Web 修改何时需要重建或刷新。',
|
|
54
|
+
peSuppressed: '未使用',
|
|
55
|
+
peCompletePersona: '此预设将 Persona 作为完整系统提示词,因此不使用这一段。',
|
|
56
|
+
peLoading: '正在读取预设…',
|
|
57
|
+
peTitle: '预设编辑',
|
|
58
|
+
peHierarchy: 'Codex 模式和其它预设处于同一级。选择一个预设编辑;内置预设先创建可编辑副本。',
|
|
59
|
+
peSelect: '选择预设',
|
|
60
|
+
peSelectPlaceholder: '选择一个预设…',
|
|
61
|
+
peEditable: '这是可编辑的用户预设。',
|
|
62
|
+
peBuiltinEdit: '内置预设只读,需要先创建副本。',
|
|
63
|
+
peCreateCopy: '创建可编辑副本',
|
|
64
|
+
peCodexSection: 'Codex 模式能力',
|
|
65
|
+
peAddCodex: '为这个预设加入 Codex 能力',
|
|
66
|
+
peAddCodexHint: '加入 Codex 提示词、工具、托管搜索和远程上下文压缩。',
|
|
67
|
+
peActivityGlobal: '活动状态是全局显示设置,由所有预设共享。',
|
|
68
|
+
peSaveCopy: '保存新预设',
|
|
69
|
+
peSaved: '已保存,在新会话中选择此预设即可使用。',
|
|
70
|
+
pmGlobalSettings: '全局设置',
|
|
71
|
+
pmRefresh: '刷新',
|
|
72
|
+
pmBuiltIn: '内置',
|
|
73
|
+
pmCustom: '自定义',
|
|
74
|
+
pmDiscard: '放弃尚未保存的修改?',
|
|
75
|
+
pmConflict: '此预设已被其他页面或文件修改,请重新打开最新版本后再保存。',
|
|
76
|
+
pmYamlError: '配置必须是有效 YAML,草稿尚未保存。',
|
|
77
|
+
pmErrorDetails: '技术详情',
|
|
78
|
+
pmSaveError: '操作未完成,填写的内容仍然保留。',
|
|
79
|
+
pmName: '名称',
|
|
80
|
+
pmDescription: '用途说明',
|
|
81
|
+
pmCancel: '取消',
|
|
82
|
+
pmSave: '保存修改',
|
|
83
|
+
}
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
import { useEffect, useRef, useState } from 'react'
|
|
2
|
+
import type { InjectFace, PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'
|
|
3
|
+
import type { RemoteResult, TypertClientRemote } from '@deepseek-ai/dsh-typert-protocol'
|
|
4
|
+
import type { CodexPresetOptions, PresetCatalog, PresetCreateInput, PresetEditorDocument, PresetEditorInput } from '../preset-contract.ts'
|
|
5
|
+
import type { PresetPromptCatalog, PresetToolCatalog } from '../tool-policy-contract.ts'
|
|
6
|
+
import { DEFAULT_CODEX_SYSTEM_PROMPT } from '../prompt.ts'
|
|
7
|
+
import { cachePresetCatalog, cachedPresetCatalog, isPresetConnectionError, readPresetWithRetry, requestPresetCatalog } from './preset-requests.ts'
|
|
8
|
+
|
|
9
|
+
export interface PresetClientRemote extends TypertClientRemote {
|
|
10
|
+
codexPresetEditor: {
|
|
11
|
+
catalog(): Promise<RemoteResult<PresetCatalog>>
|
|
12
|
+
tools?(id: string): Promise<RemoteResult<PresetToolCatalog>>
|
|
13
|
+
prompts?(id: string): Promise<RemoteResult<PresetPromptCatalog>>
|
|
14
|
+
read(id: string): Promise<RemoteResult<PresetEditorDocument>>
|
|
15
|
+
update(input: PresetEditorInput): Promise<RemoteResult<PresetEditorDocument>>
|
|
16
|
+
create(input: PresetCreateInput): Promise<RemoteResult<PresetEditorDocument>>
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
export interface PresetManagerActions { remote: PresetClientRemote; ready: Promise<void> }
|
|
20
|
+
type Props = InjectFace<{ presetManager: PresetManagerActions }> & PropsLocale<'codex'> & { readOnly?: boolean }
|
|
21
|
+
const documentCache = new WeakMap<PresetManagerActions, Map<string, { value: PresetEditorDocument; time: number }>>()
|
|
22
|
+
const CODEX_DEFAULT_ID = 'codex-collaboration'
|
|
23
|
+
function unwrap<T>(result: RemoteResult<T>): T {
|
|
24
|
+
if (result.ok) return result.value
|
|
25
|
+
throw new Error((result.error as unknown as { message?: string }).message ?? 'remote-request-failed')
|
|
26
|
+
}
|
|
27
|
+
function equalEditorState(a: PresetEditorDocument | undefined, b: PresetEditorDocument | undefined): boolean {
|
|
28
|
+
if (!a || !b) return a === b
|
|
29
|
+
return a.name === b.name && a.description === b.description && a.systemPrompt === b.systemPrompt
|
|
30
|
+
&& a.inheritPrompt === b.inheritPrompt && a.codex === b.codex
|
|
31
|
+
&& JSON.stringify(a.codexOptions) === JSON.stringify(b.codexOptions)
|
|
32
|
+
&& JSON.stringify(a.promptSections) === JSON.stringify(b.promptSections)
|
|
33
|
+
}
|
|
34
|
+
const styles = `
|
|
35
|
+
.codex-preset-editor { display:grid; gap:12px; min-width:0; font-size:13px; }
|
|
36
|
+
.codex-preset-editor label { display:grid; gap:6px; }
|
|
37
|
+
.codex-preset-editor .pe-row { display:flex; align-items:center; gap:10px; flex-wrap:wrap; }
|
|
38
|
+
.codex-preset-editor input:not([type=checkbox]), .codex-preset-editor textarea, .codex-preset-editor select { box-sizing:border-box; width:100%; padding:8px; border:1px solid var(--dsw-alias-border-l2); border-radius:6px; background:var(--dsw-alias-bg-layer-2); color:inherit; font:inherit; }
|
|
39
|
+
.codex-preset-editor textarea { resize:vertical; line-height:1.5; }
|
|
40
|
+
.codex-preset-editor button { font:inherit; padding:6px 12px; border:1px solid var(--dsw-alias-border-l2); border-radius:6px; background:var(--dsw-alias-bg-layer-2); color:inherit; cursor:pointer; }
|
|
41
|
+
.codex-preset-editor button:disabled { opacity:.5; cursor:default; }
|
|
42
|
+
.codex-preset-editor .pe-primary { background:var(--dsw-alias-label-primary); border-color:var(--dsw-alias-label-primary); color:var(--dsw-alias-bg-base); }
|
|
43
|
+
.codex-preset-editor .pe-block { display:grid; gap:9px; padding-top:12px; border-top:1px solid var(--dsw-alias-border-l2); }
|
|
44
|
+
.codex-preset-editor .pe-toggle { display:flex; align-items:flex-start; gap:9px; }
|
|
45
|
+
.codex-preset-editor .pe-toggle span { display:grid; gap:2px; }
|
|
46
|
+
.codex-preset-editor p { margin:0; font-size:12px; line-height:1.55; color:var(--dsw-alias-label-secondary); }
|
|
47
|
+
`
|
|
48
|
+
|
|
49
|
+
function optionToggle(
|
|
50
|
+
key: keyof CodexPresetOptions,
|
|
51
|
+
label: string,
|
|
52
|
+
hint: string,
|
|
53
|
+
options: CodexPresetOptions,
|
|
54
|
+
setOptions: (next: CodexPresetOptions) => void,
|
|
55
|
+
disabled: boolean,
|
|
56
|
+
) {
|
|
57
|
+
return <label className="pe-toggle" key={key}>
|
|
58
|
+
<input type="checkbox" checked={options[key]} disabled={disabled} onChange={event => setOptions({ ...options, [key]: event.target.checked })} />
|
|
59
|
+
<span><strong>{label}</strong><small>{hint}</small></span>
|
|
60
|
+
</label>
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Presets are peers: choose one to edit, or make an editable copy first. */
|
|
64
|
+
export function PresetManagerCard({ presetManager, t, readOnly: inspectOnly = false }: Props) {
|
|
65
|
+
const [catalog, setCatalog] = useState(() => cachedPresetCatalog(presetManager))
|
|
66
|
+
const [selectedId, setSelectedId] = useState('')
|
|
67
|
+
const [original, setOriginal] = useState<PresetEditorDocument>()
|
|
68
|
+
const [draft, setDraft] = useState<PresetEditorDocument>()
|
|
69
|
+
const [sourceId, setSourceId] = useState('')
|
|
70
|
+
const [copyMode, setCopyMode] = useState(false)
|
|
71
|
+
const [codexEnabled, setCodexEnabled] = useState(false)
|
|
72
|
+
const [busy, setBusy] = useState(false)
|
|
73
|
+
const [error, setError] = useState('')
|
|
74
|
+
const [errorAction, setErrorAction] = useState<'catalog' | 'read' | 'save'>('read')
|
|
75
|
+
const [notice, setNotice] = useState('')
|
|
76
|
+
const alive = useRef(true)
|
|
77
|
+
const request = useRef(0)
|
|
78
|
+
if (!documentCache.has(presetManager)) documentCache.set(presetManager, new Map())
|
|
79
|
+
const cache = documentCache.get(presetManager)!
|
|
80
|
+
const remote = presetManager.remote.codexPresetEditor
|
|
81
|
+
const dirty = !!draft && (!original || !equalEditorState(draft, original) || codexEnabled !== draft.codex)
|
|
82
|
+
|
|
83
|
+
async function run(work: () => Promise<void>) {
|
|
84
|
+
setBusy(true); setError(''); setNotice('')
|
|
85
|
+
try { await presetManager.ready; if (alive.current) await work() }
|
|
86
|
+
catch (cause) { if (alive.current) setError(cause instanceof Error ? cause.message : String(cause)) }
|
|
87
|
+
finally { if (alive.current) setBusy(false) }
|
|
88
|
+
}
|
|
89
|
+
async function load(id: string, confirmDirty = true): Promise<void> {
|
|
90
|
+
if (!id) return
|
|
91
|
+
if (confirmDirty && dirty && !window.confirm(t('pmDiscard'))) return
|
|
92
|
+
const ticket = ++request.current
|
|
93
|
+
setSelectedId(id); setError(''); setNotice(''); setErrorAction('read')
|
|
94
|
+
const accept = (value: PresetEditorDocument) => {
|
|
95
|
+
if (!alive.current || ticket !== request.current) return
|
|
96
|
+
setSelectedId(id); setSourceId(id); setOriginal(value); setDraft(value)
|
|
97
|
+
setCopyMode(false); setCodexEnabled(value.codex)
|
|
98
|
+
}
|
|
99
|
+
const cached = cache.get(id)
|
|
100
|
+
if (cached && Date.now() - cached.time < 60_000) { accept(cached.value); return }
|
|
101
|
+
setDraft(undefined); setOriginal(undefined); setBusy(true)
|
|
102
|
+
try {
|
|
103
|
+
await presetManager.ready
|
|
104
|
+
const value = await readPresetWithRetry(() => remote.read(id).then(unwrap), () => alive.current && ticket === request.current)
|
|
105
|
+
cache.set(id, { value, time: Date.now() }); accept(value)
|
|
106
|
+
} catch (cause) { if (alive.current && ticket === request.current) setError(String(cause)) }
|
|
107
|
+
finally { if (alive.current && ticket === request.current) setBusy(false) }
|
|
108
|
+
}
|
|
109
|
+
async function refresh(): Promise<void> {
|
|
110
|
+
setErrorAction('catalog')
|
|
111
|
+
const value = await readPresetWithRetry(() => requestPresetCatalog(presetManager, true), () => alive.current)
|
|
112
|
+
if (!alive.current) return
|
|
113
|
+
setCatalog(value)
|
|
114
|
+
const current = value.presets.some(row => row.id === selectedId) ? selectedId
|
|
115
|
+
: value.presets.some(row => row.id === CODEX_DEFAULT_ID) ? CODEX_DEFAULT_ID : value.presets[0]?.id ?? ''
|
|
116
|
+
if (current) await load(current, false)
|
|
117
|
+
else { setSelectedId(''); setOriginal(undefined); setDraft(undefined) }
|
|
118
|
+
}
|
|
119
|
+
useEffect(() => {
|
|
120
|
+
alive.current = true
|
|
121
|
+
const cached = cachedPresetCatalog(presetManager)
|
|
122
|
+
if (cached === undefined) void run(refresh)
|
|
123
|
+
else if (!selectedId) void load(cached.presets.some(row => row.id === CODEX_DEFAULT_ID) ? CODEX_DEFAULT_ID : cached.presets[0]?.id ?? '', false)
|
|
124
|
+
return () => { alive.current = false }
|
|
125
|
+
}, [presetManager])
|
|
126
|
+
useEffect(() => {
|
|
127
|
+
if (!dirty) return
|
|
128
|
+
const guard = (event: BeforeUnloadEvent) => { event.preventDefault(); event.returnValue = '' }
|
|
129
|
+
window.addEventListener('beforeunload', guard)
|
|
130
|
+
return () => window.removeEventListener('beforeunload', guard)
|
|
131
|
+
}, [dirty])
|
|
132
|
+
function patch(value: Partial<PresetEditorDocument>) { if (draft) setDraft({ ...draft, ...value }) }
|
|
133
|
+
function beginCopy(): void {
|
|
134
|
+
if (inspectOnly || !draft || !sourceId) return
|
|
135
|
+
setCopyMode(true); setCodexEnabled(draft.codex)
|
|
136
|
+
setOriginal({ ...draft })
|
|
137
|
+
setDraft({ ...draft, id: '', revision: '', editable: true, name: `${draft.name} · ${t('pmCustom')}` })
|
|
138
|
+
}
|
|
139
|
+
function save(): void {
|
|
140
|
+
if (inspectOnly || !draft || busy || !draft.name.trim()) return
|
|
141
|
+
setErrorAction('save')
|
|
142
|
+
void run(async () => {
|
|
143
|
+
const options = codexEnabled ? draft.codexOptions : undefined
|
|
144
|
+
const payload = { name: draft.name, description: draft.description, systemPrompt: draft.systemPrompt,
|
|
145
|
+
promptSections: draft.promptSections.filter(section => section.editable && (codexEnabled || section.id !== 'codex:base')),
|
|
146
|
+
inheritPrompt: draft.inheritPrompt, enableCodex: codexEnabled, ...(options === undefined ? {} : { codexOptions: options }) }
|
|
147
|
+
const value = unwrap(await (copyMode
|
|
148
|
+
? remote.create({ ...payload, sourceId })
|
|
149
|
+
: remote.update({ ...payload, id: draft.id, revision: draft.revision })))
|
|
150
|
+
if (!alive.current) return
|
|
151
|
+
setSelectedId(value.id); setSourceId(value.id); setOriginal(value); setDraft(value)
|
|
152
|
+
cache.set(value.id, { value, time: Date.now() })
|
|
153
|
+
setCopyMode(false); setCodexEnabled(value.codex); setNotice(t('peSaved'))
|
|
154
|
+
if (catalog) {
|
|
155
|
+
const row = { id: value.id, name: value.name, description: value.description, editable: value.editable,
|
|
156
|
+
isDefault: catalog.presets.find(item => item.id === value.id)?.isDefault ?? false }
|
|
157
|
+
const presets = catalog.presets.some(item => item.id === value.id)
|
|
158
|
+
? catalog.presets.map(item => item.id === value.id ? row : item) : [...catalog.presets, row]
|
|
159
|
+
cachePresetCatalog(presetManager, { ...catalog, presets }); setCatalog({ ...catalog, presets })
|
|
160
|
+
}
|
|
161
|
+
})
|
|
162
|
+
}
|
|
163
|
+
const selectedRow = catalog?.presets.find(row => row.id === selectedId)
|
|
164
|
+
const readOnly = inspectOnly || (!!draft && !draft.editable && !copyMode)
|
|
165
|
+
const options = draft?.codexOptions
|
|
166
|
+
return <section className="codex-preset-editor" aria-label={t('peTitle')} aria-busy={busy}>
|
|
167
|
+
<style>{styles}</style>
|
|
168
|
+
<div className="pe-row" style={{ justifyContent:'space-between' }}>
|
|
169
|
+
<strong>{t('peTitle')}</strong>
|
|
170
|
+
<button type="button" disabled={busy} onClick={() => { if (dirty && !window.confirm(t('pmDiscard'))) return; cache.clear(); void run(refresh) }}>{t('pmRefresh')}</button>
|
|
171
|
+
</div>
|
|
172
|
+
<p>{t('peHierarchy')}</p>
|
|
173
|
+
<label>{t('peSelect')}<select value={selectedId} disabled={busy || !catalog} onChange={event => { void load(event.target.value) }}>
|
|
174
|
+
<option value="">{t('peSelectPlaceholder')}</option>
|
|
175
|
+
{catalog?.presets.map(row => <option key={row.id} value={row.id}>{row.name}{row.editable ? '' : ` · ${t('pmBuiltIn')}`}</option>)}
|
|
176
|
+
</select></label>
|
|
177
|
+
{selectedRow && <p>{selectedRow.editable ? t('peEditable') : t(catalog?.authorable ? 'peBuiltinEdit' : 'pmRegistryReadOnly')}</p>}
|
|
178
|
+
{error && <div role="alert">
|
|
179
|
+
<p>{errorAction !== 'save'
|
|
180
|
+
? t(isPresetConnectionError(error) ? 'peConnectionError' : 'peReadError')
|
|
181
|
+
: error.includes('preset-conflict') ? t('pmConflict') : error.includes('invalid-preset-yaml') ? t('pmYamlError') : t('pmSaveError')}</p>
|
|
182
|
+
{errorAction !== 'save' && <div className="pe-row">
|
|
183
|
+
<button type="button" disabled={busy} onClick={() => { if (errorAction === 'catalog' || !selectedId) void run(refresh); else { cache.delete(selectedId); void load(selectedId, false) } }}>{t('peRetryRead')}</button>
|
|
184
|
+
{!draft && isPresetConnectionError(error) && <button type="button" onClick={() => window.location.reload()}>{t('peReconnect')}</button>}
|
|
185
|
+
</div>}
|
|
186
|
+
<details><summary>{t('pmErrorDetails')}</summary><pre style={{ whiteSpace:'pre-wrap' }}>{error}</pre></details>
|
|
187
|
+
</div>}
|
|
188
|
+
{notice && <p role="status">{notice}</p>}
|
|
189
|
+
{busy && !draft && <p role="status">{t('peLoading')}</p>}
|
|
190
|
+
{draft && <>
|
|
191
|
+
<label>{t('pmName')}<input value={draft.name} maxLength={200} disabled={busy || readOnly} onChange={event => patch({ name:event.target.value })} /></label>
|
|
192
|
+
<label>{t('pmDescription')}<input value={draft.description} maxLength={4000} disabled={busy || readOnly} onChange={event => patch({ description:event.target.value })} /></label>
|
|
193
|
+
{!inspectOnly && !copyMode && catalog?.authorable && <button type="button" disabled={busy} onClick={beginCopy}>{t('peCreateCopy')}</button>}
|
|
194
|
+
<div className="pe-block">
|
|
195
|
+
<strong>{t('peSystemPrompt')}</strong>
|
|
196
|
+
<p>{t('peSectionsHint')}</p>
|
|
197
|
+
{draft.promptSections.map(section => <details key={section.id}>
|
|
198
|
+
<summary style={{ cursor: 'pointer', padding: '6px 0' }}>{section.label}{section.suppressed ? ` · ${t('peSuppressed')}` : ''}</summary>
|
|
199
|
+
{section.id === 'harness:source' && <p>{t('peDshSourcePrompt')}</p>}
|
|
200
|
+
{section.id === 'app:web-surface' && <p>{t('peDshWebPrompt')}</p>}
|
|
201
|
+
<textarea aria-label={section.label} rows={section.id === 'codex:base' ? 12 : 5} value={section.text}
|
|
202
|
+
disabled={busy || readOnly || !section.editable}
|
|
203
|
+
onChange={event => patch({ promptSections: draft.promptSections.map(item => item.id === section.id ? { ...item, text: event.target.value } : item),
|
|
204
|
+
...(section.id === 'codex:base' ? { systemPrompt: event.target.value, inheritPrompt: false } : {}) })} />
|
|
205
|
+
{section.suppressed ? <p>{t('peCompletePersona')}</p> : !section.editable && <p>{t('peDynamicPrompt')}</p>}
|
|
206
|
+
</details>)}
|
|
207
|
+
</div>
|
|
208
|
+
{!readOnly && <>
|
|
209
|
+
<div className="pe-block">
|
|
210
|
+
<strong>{t('peCodexSection')}</strong>
|
|
211
|
+
{!draft.codex && <label className="pe-toggle"><input type="checkbox" checked={codexEnabled} disabled={busy} onChange={event => {
|
|
212
|
+
const enabled = event.target.checked
|
|
213
|
+
setCodexEnabled(enabled)
|
|
214
|
+
if (enabled) {
|
|
215
|
+
const extras = [
|
|
216
|
+
{ id: 'codex:base', label: 'Codex 操作提示词', text: DEFAULT_CODEX_SYSTEM_PROMPT, editable: true },
|
|
217
|
+
]
|
|
218
|
+
patch({ promptSections: [...draft.promptSections.map(s => s.suppressed ? { ...s, suppressed: undefined, editable: true } : s), ...extras.filter(item => !draft.promptSections.some(s => s.id === item.id))] })
|
|
219
|
+
} else patch({ promptSections: draft.promptSections.filter(s => original?.promptSections.some(item => item.id === s.id)).map(s => {
|
|
220
|
+
const source = original?.promptSections.find(item => item.id === s.id)
|
|
221
|
+
return source?.suppressed ? { ...s, suppressed: true, editable: false } : s
|
|
222
|
+
}) })
|
|
223
|
+
}} /><span><strong>{t('peAddCodex')}</strong><small>{t('peAddCodexHint')}</small></span></label>}
|
|
224
|
+
{codexEnabled && options && <>
|
|
225
|
+
{optionToggle('hostedWebSearchEnabled', t('capabilityWebSearch'), t('capabilityWebSearchHint'), options, next => patch({ codexOptions: next }), busy)}
|
|
226
|
+
{optionToggle('remoteCompactionEnabled', t('capabilityCompaction'), t('capabilityCompactionHint'), options, next => patch({ codexOptions: next }), busy)}
|
|
227
|
+
{optionToggle('terminalToolsEnabled', t('capabilityTerminal'), t('capabilityTerminalHint'), options, next => patch({ codexOptions: next }), busy)}
|
|
228
|
+
{optionToggle('patchToolEnabled', t('capabilityPatch'), t('capabilityPatchHint'), options, next => patch({ codexOptions: next }), busy)}
|
|
229
|
+
{optionToggle('planToolEnabled', t('capabilityPlan'), t('capabilityPlanHint'), options, next => patch({ codexOptions: next }), busy)}
|
|
230
|
+
{optionToggle('promptEnabled', t('capabilityPrompt'), t('capabilityPromptHint'), options, next => patch({ codexOptions: next }), busy)}
|
|
231
|
+
<p>{t('peActivityGlobal')}</p>
|
|
232
|
+
</>}
|
|
233
|
+
</div>
|
|
234
|
+
<div className="pe-row"><button type="button" className="pe-primary" disabled={busy || !catalog?.authorable || !draft.name.trim() || !dirty} onClick={save}>{copyMode ? t('peSaveCopy') : t('pmSave')}</button>
|
|
235
|
+
{copyMode && <button type="button" disabled={busy} onClick={() => { void load(sourceId, false) }}>{t('pmCancel')}</button>}
|
|
236
|
+
{!copyMode && <button type="button" disabled={busy} onClick={() => { void load(draft.id, false) }}>{t('pmCancel')}</button>}
|
|
237
|
+
</div>
|
|
238
|
+
</>}
|
|
239
|
+
</>}
|
|
240
|
+
</section>
|
|
241
|
+
}
|
|
242
|
+
/** A fixed-ID declaration viewer: no second picker and no write/copy actions. */
|
|
243
|
+
export function PresetDefinitionCard({ presetManager, id, t }: { presetManager: PresetManagerActions; id: string } & PropsLocale<'codex'>) {
|
|
244
|
+
const [value, setValue] = useState<PresetEditorDocument>()
|
|
245
|
+
const [loading, setLoading] = useState(true)
|
|
246
|
+
const [error, setError] = useState('')
|
|
247
|
+
const request = useRef(0)
|
|
248
|
+
const alive = useRef(true)
|
|
249
|
+
async function load(refresh = false): Promise<void> {
|
|
250
|
+
const ticket = ++request.current
|
|
251
|
+
setLoading(true); setError('')
|
|
252
|
+
try {
|
|
253
|
+
await presetManager.ready
|
|
254
|
+
const cache = documentCache.get(presetManager) ?? new Map<string, { value: PresetEditorDocument; time: number }>()
|
|
255
|
+
documentCache.set(presetManager, cache)
|
|
256
|
+
const cached = cache.get(id)
|
|
257
|
+
const document = !refresh && cached && Date.now() - cached.time < 60_000 ? cached.value
|
|
258
|
+
: await readPresetWithRetry(() => presetManager.remote.codexPresetEditor.read(id).then(unwrap), () => alive.current && ticket === request.current)
|
|
259
|
+
if (document.id !== id) throw new Error('preset-document-mismatch')
|
|
260
|
+
cache.set(id, { value: document, time: Date.now() })
|
|
261
|
+
if (alive.current && ticket === request.current) setValue(document)
|
|
262
|
+
} catch (cause) { if (alive.current && ticket === request.current) setError(cause instanceof Error ? cause.message : String(cause)) }
|
|
263
|
+
finally { if (alive.current && ticket === request.current) setLoading(false) }
|
|
264
|
+
}
|
|
265
|
+
useEffect(() => {
|
|
266
|
+
alive.current = true; void load()
|
|
267
|
+
return () => { alive.current = false; request.current++ }
|
|
268
|
+
}, [presetManager, id])
|
|
269
|
+
const shown = value?.id === id ? value : undefined
|
|
270
|
+
return <section className="codex-preset-editor" aria-label={t('settingsDefinition')} aria-busy={loading}>
|
|
271
|
+
<style>{styles}</style>
|
|
272
|
+
<h3>{t('settingsDefinition')}</h3><code>{id}</code>
|
|
273
|
+
<button type="button" disabled={loading} onClick={() => { void load(true) }}>{t('pmRefresh')}</button>
|
|
274
|
+
{loading && !shown && <p role="status">{t('peLoading')}</p>}
|
|
275
|
+
{error && <p role="alert">{t('peReadError')}</p>}
|
|
276
|
+
{shown && <><strong>{shown.name}</strong><p>{shown.description}</p>
|
|
277
|
+
<pre style={{ whiteSpace: 'pre-wrap', overflowWrap: 'anywhere', margin: 0 }}>{shown.composition || JSON.stringify({ id: shown.id, name: shown.name, promptSections: shown.promptSections }, null, 2)}</pre>
|
|
278
|
+
</>}
|
|
279
|
+
</section>
|
|
280
|
+
}
|
|
281
|
+
export default PresetManagerCard
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import type { PresetCatalog } from '../preset-contract.ts'
|
|
2
|
+
import type { PresetManagerActions } from './preset-manager.tsx'
|
|
3
|
+
import type { PresetPromptCatalog, PresetToolCatalog } from '../tool-policy-contract.ts'
|
|
4
|
+
|
|
5
|
+
const catalogs = new WeakMap<PresetManagerActions, PresetCatalog>()
|
|
6
|
+
const catalogRequests = new WeakMap<PresetManagerActions, Promise<PresetCatalog>>()
|
|
7
|
+
|
|
8
|
+
export function cachedPresetCatalog(manager: PresetManagerActions): PresetCatalog | undefined {
|
|
9
|
+
return catalogs.get(manager)
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function cachePresetCatalog(manager: PresetManagerActions, catalog: PresetCatalog): void {
|
|
13
|
+
catalogs.set(manager, catalog)
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** One cache and one in-flight catalog read for every surface using this manager. */
|
|
17
|
+
export function requestPresetCatalog(manager: PresetManagerActions, refresh = false): Promise<PresetCatalog> {
|
|
18
|
+
const pending = catalogRequests.get(manager)
|
|
19
|
+
if (pending !== undefined) return pending
|
|
20
|
+
const cached = catalogs.get(manager)
|
|
21
|
+
if (!refresh && cached !== undefined) return Promise.resolve(cached)
|
|
22
|
+
const request = (async () => {
|
|
23
|
+
await manager.ready
|
|
24
|
+
const result = await manager.remote.codexPresetEditor.catalog()
|
|
25
|
+
if (!result.ok) throw new Error(result.error.message ?? 'preset-catalog-unavailable')
|
|
26
|
+
catalogs.set(manager, result.value)
|
|
27
|
+
return result.value
|
|
28
|
+
})()
|
|
29
|
+
catalogRequests.set(manager, request)
|
|
30
|
+
void request.finally(() => {
|
|
31
|
+
if (catalogRequests.get(manager) === request) catalogRequests.delete(manager)
|
|
32
|
+
}).catch(() => {})
|
|
33
|
+
return request
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const toolCatalogs = new WeakMap<PresetManagerActions, Map<string, PresetToolCatalog>>()
|
|
37
|
+
const toolRequests = new WeakMap<PresetManagerActions, Map<string, Promise<PresetToolCatalog>>>()
|
|
38
|
+
|
|
39
|
+
export function cachedPresetTools(manager: PresetManagerActions, id: string): PresetToolCatalog | undefined {
|
|
40
|
+
return toolCatalogs.get(manager)?.get(id)
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** The requested preset owns this snapshot; never substitute current-Agent tools. */
|
|
44
|
+
export function requestPresetTools(manager: PresetManagerActions, id: string, refresh = false): Promise<PresetToolCatalog> {
|
|
45
|
+
const pending = toolRequests.get(manager)?.get(id)
|
|
46
|
+
if (pending !== undefined) return pending
|
|
47
|
+
const cached = cachedPresetTools(manager, id)
|
|
48
|
+
if (!refresh && cached !== undefined) return Promise.resolve(cached)
|
|
49
|
+
const requests = toolRequests.get(manager) ?? new Map<string, Promise<PresetToolCatalog>>()
|
|
50
|
+
toolRequests.set(manager, requests)
|
|
51
|
+
const request = (async () => {
|
|
52
|
+
await manager.ready
|
|
53
|
+
const remote = manager.remote.codexPresetEditor
|
|
54
|
+
if (typeof remote.tools !== 'function') throw new Error('preset-tools-unavailable')
|
|
55
|
+
const result = await remote.tools(id)
|
|
56
|
+
if (!result.ok) throw new Error(result.error.message ?? 'preset-tools-unavailable')
|
|
57
|
+
if (result.value.preset !== id || result.value.registeredOnly !== true || !Array.isArray(result.value.tools)) {
|
|
58
|
+
throw new Error('preset-tools-mismatched-snapshot')
|
|
59
|
+
}
|
|
60
|
+
const catalogs = toolCatalogs.get(manager) ?? new Map<string, PresetToolCatalog>()
|
|
61
|
+
catalogs.set(id, result.value); toolCatalogs.set(manager, catalogs)
|
|
62
|
+
return result.value
|
|
63
|
+
})()
|
|
64
|
+
requests.set(id, request)
|
|
65
|
+
void request.finally(() => { if (requests.get(id) === request) requests.delete(id) }).catch(() => {})
|
|
66
|
+
return request
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const promptCatalogs = new WeakMap<PresetManagerActions, Map<string, PresetPromptCatalog>>()
|
|
70
|
+
const promptRequests = new WeakMap<PresetManagerActions, Map<string, Promise<PresetPromptCatalog>>>()
|
|
71
|
+
|
|
72
|
+
export function cachedPresetPrompts(manager: PresetManagerActions, id: string): PresetPromptCatalog | undefined {
|
|
73
|
+
return promptCatalogs.get(manager)?.get(id)
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function requestPresetPrompts(manager: PresetManagerActions, id: string, refresh = false): Promise<PresetPromptCatalog> {
|
|
77
|
+
const pending = promptRequests.get(manager)?.get(id)
|
|
78
|
+
if (pending !== undefined) return pending
|
|
79
|
+
const cached = cachedPresetPrompts(manager, id)
|
|
80
|
+
if (!refresh && cached !== undefined) return Promise.resolve(cached)
|
|
81
|
+
const requests = promptRequests.get(manager) ?? new Map<string, Promise<PresetPromptCatalog>>()
|
|
82
|
+
promptRequests.set(manager, requests)
|
|
83
|
+
const request = (async () => {
|
|
84
|
+
await manager.ready
|
|
85
|
+
const remote = manager.remote.codexPresetEditor
|
|
86
|
+
if (typeof remote.prompts !== 'function') throw new Error('preset-prompts-unavailable')
|
|
87
|
+
const result = await remote.prompts(id)
|
|
88
|
+
if (!result.ok) throw new Error(result.error.message ?? 'preset-prompts-unavailable')
|
|
89
|
+
if (result.value.preset !== id || !Array.isArray(result.value.sections)) throw new Error('preset-prompts-mismatched-snapshot')
|
|
90
|
+
const catalogs = promptCatalogs.get(manager) ?? new Map<string, PresetPromptCatalog>()
|
|
91
|
+
catalogs.set(id, result.value); promptCatalogs.set(manager, catalogs)
|
|
92
|
+
return result.value
|
|
93
|
+
})()
|
|
94
|
+
requests.set(id, request)
|
|
95
|
+
void request.finally(() => { if (requests.get(id) === request) requests.delete(id) }).catch(() => {})
|
|
96
|
+
return request
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Only transport failures from a read can be retried without duplicating writes. */
|
|
100
|
+
export function isPresetConnectionError(error: unknown): boolean {
|
|
101
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
102
|
+
return /Failed to fetch|NetworkError|Load failed|network request failed|no active Connection|connection.*(?:closed|offline)/i.test(message)
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export async function readPresetWithRetry<T>(read: () => Promise<T>, active: () => boolean): Promise<T> {
|
|
106
|
+
try { return await read() }
|
|
107
|
+
catch (error) {
|
|
108
|
+
if (!isPresetConnectionError(error) || !active()) throw error
|
|
109
|
+
await new Promise(resolve => setTimeout(resolve, 300))
|
|
110
|
+
if (!active()) throw error
|
|
111
|
+
return read()
|
|
112
|
+
}
|
|
113
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** Preset identity moved from the legacy summary field to projectionValues. */
|
|
2
|
+
export function agentPresetFromSession(summary: {
|
|
3
|
+
readonly agentPreset?: unknown
|
|
4
|
+
readonly projectionValues?: Readonly<Record<string, unknown>> | undefined
|
|
5
|
+
} | undefined): string | undefined {
|
|
6
|
+
const projections = summary?.projectionValues
|
|
7
|
+
const value = projections !== undefined && Object.hasOwn(projections, 'agentPreset')
|
|
8
|
+
? projections.agentPreset
|
|
9
|
+
: summary?.agentPreset
|
|
10
|
+
return typeof value === 'string' ? value : undefined
|
|
11
|
+
}
|