@dsh-ray/assistant-delivery 0.3.3 → 0.3.5

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 (42) hide show
  1. package/README.md +5 -4
  2. package/lib/agent-runtime.d.ts +11 -3
  3. package/lib/agent-runtime.d.ts.map +1 -1
  4. package/lib/agent-runtime.js +295 -37
  5. package/lib/agent-runtime.js.map +1 -1
  6. package/lib/command-catalog.d.ts +42 -0
  7. package/lib/command-catalog.d.ts.map +1 -0
  8. package/lib/command-catalog.js +248 -0
  9. package/lib/command-catalog.js.map +1 -0
  10. package/lib/config-control.d.ts +158 -0
  11. package/lib/config-control.d.ts.map +1 -0
  12. package/lib/config-control.js +1406 -0
  13. package/lib/config-control.js.map +1 -0
  14. package/lib/index.d.ts +4 -1
  15. package/lib/index.d.ts.map +1 -1
  16. package/lib/index.js +4 -1
  17. package/lib/index.js.map +1 -1
  18. package/lib/service.d.ts +10 -1
  19. package/lib/service.d.ts.map +1 -1
  20. package/lib/service.js +483 -3
  21. package/lib/service.js.map +1 -1
  22. package/lib/session-commands.d.ts +12 -0
  23. package/lib/session-commands.d.ts.map +1 -1
  24. package/lib/session-commands.js +57 -0
  25. package/lib/session-commands.js.map +1 -1
  26. package/lib/sqlite.d.ts.map +1 -1
  27. package/lib/sqlite.js +1 -0
  28. package/lib/sqlite.js.map +1 -1
  29. package/lib/stderr-logger.d.ts +24 -0
  30. package/lib/stderr-logger.d.ts.map +1 -0
  31. package/lib/stderr-logger.js +89 -0
  32. package/lib/stderr-logger.js.map +1 -0
  33. package/lib/store.d.ts +17 -1
  34. package/lib/store.d.ts.map +1 -1
  35. package/lib/store.js +333 -4
  36. package/lib/store.js.map +1 -1
  37. package/lib/types.d.ts +94 -1
  38. package/lib/types.d.ts.map +1 -1
  39. package/lib/types.js.map +1 -1
  40. package/lib/version.d.ts +1 -1
  41. package/lib/version.js +1 -1
  42. package/package.json +10 -10
package/lib/service.js CHANGED
@@ -10,6 +10,7 @@ import { SessionId } from '@deepseek-ai/dsh-session';
10
10
  import Schema from '@deepseek-ai/schemastery';
11
11
  import { RestartStore } from './restart-store.js';
12
12
  import { restartDigest } from './restart-runtime.js';
13
+ import { installDiagnosticStderrExporter } from './stderr-logger.js';
13
14
  import { version } from './version.js';
14
15
  import { acceptanceCanonicalJson, goalDefinitionSituation } from '@dsh-ray/task-acceptance-contract';
15
16
  import { approvalReviewerOf, } from '@dsh-ray/assistant-policy';
@@ -22,6 +23,7 @@ import { ASSISTANT_GROWTH_CONTRACT_VERSION, defaultRayPluginStatePath, growthObj
22
23
  import { DeliveryAdapterRegistry, DeliveryCoordinator, InboundCoordinator, } from './coordinator.js';
23
24
  import { DeliveryStore, DeliveryStoreError, } from './store.js';
24
25
  import { DshDeliveryRuntime, redactOwnerLearningReply } from './agent-runtime.js';
26
+ import { listLarkSlashCommandSpecs } from './command-catalog.js';
25
27
  import { parseOwnerVetoArgs } from './session-commands.js';
26
28
  import { RayWorkerTicketRuntime } from './ray-worker-runtime.js';
27
29
  import { DeliverySessionLeases, SessionLeaseUnavailable } from './session-lease-runtime.js';
@@ -41,6 +43,7 @@ import { collectDeliveryVersionReport, } from './version-query.js';
41
43
  import { deliveryT1PreferenceKeys, deliveryT1PreferenceValues } from './learning-command.js';
42
44
  import { assertReplyReplayAllowed, blockAgentRepliesForReplay as createReplyReplayBlock, } from './reply-replay.js';
43
45
  import { feedbackSignalInput, naturalOwnerReplyWithoutQuotes, parseFeedbackCommand, parseNaturalObjectiveFeedback, parseNaturalOwnerReply, objectiveStateMessage, classifyNaturalPreferenceDirective, observedResponseLanguage, } from './feedback-command.js';
46
+ import { applyNonPreferenceConfigMutation, applyOwnerConsoleConversationMutation, buildConfigPickerSnapshot, OWNER_CONSOLE_PROCESS_LOGS_KEY, parseT1ConversationSelections, readOwnerConsoleShowProcessLogs, redactConfigSecret, T1_TEXT_KEY_ALIASES, validateOwnerConsoleConversationMutation, } from './config-control.js';
44
47
  import { DELIVERY_PREFERENCE_PROJECTION_PROTOCOL, TRUSTED_DELIVERY_PRESENTATION_PRODUCER_PROTOCOL, } from './types.js';
45
48
  const trustedDeliveryPreferenceProducers = new WeakSet();
46
49
  const deliveryPreferenceProducerProbe = Symbol('assistant-delivery.preference-producer-probe');
@@ -349,6 +352,7 @@ const configSchema = Schema.object({
349
352
  agentGoalContinuationTimeoutMs: Schema.number().step(1).min(0).max(300_000).default(0),
350
353
  modelPickerTtlMs: Schema.number().step(1).min(60_000).max(86_400_000).default(900_000),
351
354
  permissionPickerTtlMs: Schema.number().step(1).min(60_000).max(86_400_000).default(900_000),
355
+ configPickerTtlMs: Schema.number().step(1).min(60_000).max(86_400_000).default(900_000),
352
356
  toolApprovalTtlMs: Schema.number().step(1).min(1_000).max(300_000).default(300_000),
353
357
  toolApprovalPreparationTimeoutMs: Schema.number().step(1).min(100).max(30_000).default(10_000),
354
358
  attentionAttachOverCap: Schema.boolean().default(true),
@@ -932,6 +936,7 @@ export class AssistantDeliveryService extends Service {
932
936
  }
933
937
  mkdirSync(config.spoolPath, { recursive: true, mode: 0o700 });
934
938
  chmodSync(config.spoolPath, 0o700);
939
+ installDiagnosticStderrExporter(ctx);
935
940
  let ownerRoutes;
936
941
  try {
937
942
  ownerRoutes = config.ownerRoutes.map(route => canonicalOwnerRouteAuthority(route));
@@ -1257,6 +1262,9 @@ export class AssistantDeliveryService extends Service {
1257
1262
  recordInterruptedTurnSummary: (inboxId, failureCode, summary) => this.deliveryStore.recordInterruptedTurnSummary({ inboxId, failureCode, summary }),
1258
1263
  modelPickerTtlMs: config.modelPickerTtlMs,
1259
1264
  permissionPickerTtlMs: config.permissionPickerTtlMs,
1265
+ configPickerTtlMs: config.configPickerTtlMs,
1266
+ buildConfigPicker: (binding, envelope, activeCategory) => this.buildConfigPickerForCommand(binding, envelope, activeCategory),
1267
+ applyConversationPreferenceMutation: (binding, envelope, pairs) => this.applyConversationPreferenceMutation(binding, envelope, pairs),
1260
1268
  getModelSelection: conversation => this.deliveryStore.getModelSelection(conversation),
1261
1269
  clearStaleModelReasoningEffort: (conversation, expected) => this.deliveryStore.clearStaleModelReasoningEffort({ conversation, expected }),
1262
1270
  imageMaterializer,
@@ -1265,7 +1273,12 @@ export class AssistantDeliveryService extends Service {
1265
1273
  isOwnerFeedbackController: (binding, envelope) => this.isOwnerFeedbackController(binding, envelope),
1266
1274
  authorizeOwnerPreferenceFeedback: (binding, envelope, selections) => this.authorizeOwnerPreferenceFeedback(binding, envelope, selections),
1267
1275
  dispatchPreferenceFeedback: events => this.dispatchPreferenceFeedback(events),
1268
- replyCompletedPreferenceTurn: (agent, binding, envelope, reply) => this.replyCompletedPreferenceTurn(agent, binding, envelope, reply),
1276
+ replyCompletedPreferenceTurn: (agent, binding, envelope, reply) => this.replyCompletedPreferenceTurn(agent, binding, envelope, {
1277
+ text: reply.text,
1278
+ ...(reply.format === undefined ? {} : { format: reply.format === 'config-picker' ? 'plain' : reply.format }),
1279
+ ...(reply.modelPicker === undefined ? {} : { modelPicker: reply.modelPicker }),
1280
+ ...(reply.permissionPicker === undefined ? {} : { permissionPicker: reply.permissionPicker }),
1281
+ }),
1269
1282
  dispatchObjectiveFeedback: (binding, envelope, objectiveStatus) => this.dispatchObjectiveFeedback(binding, envelope, objectiveStatus),
1270
1283
  dispatchNaturalObjectiveFeedback: (binding, envelope) => this.dispatchNaturalObjectiveFeedback(binding, envelope),
1271
1284
  dispatchWorkflowCommand: (binding, envelope, command) => this.dispatchWorkflowCommand(binding, envelope, command),
@@ -1300,6 +1313,7 @@ export class AssistantDeliveryService extends Service {
1300
1313
  text: reply.text,
1301
1314
  replyToEventId: eventId,
1302
1315
  ...(reply.format === undefined ? {} : { format: reply.format }),
1316
+ ...(reply.configPicker === undefined ? {} : { configPicker: reply.configPicker }),
1303
1317
  ...(reply.modelPicker === undefined ? {} : { modelPicker: reply.modelPicker }),
1304
1318
  ...(reply.permissionPicker === undefined ? {} : { permissionPicker: reply.permissionPicker }),
1305
1319
  });
@@ -1768,6 +1782,456 @@ export class AssistantDeliveryService extends Service {
1768
1782
  const picker = record.intent.modelPicker;
1769
1783
  return picker === undefined || Date.now() >= picker.expiresAt ? undefined : picker;
1770
1784
  }
1785
+ configOperationId(conversation, eventId) {
1786
+ return `cfg:${createHash('sha256').update(JSON.stringify([conversation, eventId])).digest('hex').slice(0, 24)}`;
1787
+ }
1788
+ async readExplainReceiptForCallback(binding, operationId) {
1789
+ const sink = this.preferenceFeedbackSink;
1790
+ if (sink === undefined
1791
+ || sink.registration.generation !== this.preferenceProducerGeneration
1792
+ || !registrationOwnedByPreference(sink.registration)
1793
+ || typeof sink.registration.control !== 'function') {
1794
+ return undefined;
1795
+ }
1796
+ const principalLineage = this.ownerLineageForBinding(binding);
1797
+ const admissionCursor = this.deliveryStore.latestAdmissionCursor();
1798
+ if (principalLineage === undefined || admissionCursor === undefined)
1799
+ return undefined;
1800
+ const request = Object.freeze({
1801
+ scope: Object.freeze({ workspace: binding.workspace, preset: binding.agentPreset }),
1802
+ principalId: externalPrincipalId(binding.principal),
1803
+ principalLineage,
1804
+ admissionCursor,
1805
+ action: 'explain',
1806
+ occurredAt: Date.now(),
1807
+ idempotencyKey: `config-explain:${createHash('sha256').update(JSON.stringify([
1808
+ binding.id, binding.version, operationId, admissionCursor.epoch, admissionCursor.sequence,
1809
+ ])).digest('hex')}`,
1810
+ });
1811
+ try {
1812
+ await this.drainPreferenceProjections();
1813
+ if (this.deliveryStore.hasBlockingPreferenceProjectionBefore(request))
1814
+ return undefined;
1815
+ const receipt = await sink.registration.control(request);
1816
+ validateLearningControlReceipt(receipt, request);
1817
+ return receipt;
1818
+ }
1819
+ catch {
1820
+ return undefined;
1821
+ }
1822
+ }
1823
+ async buildConfigPickerSnapshotForBinding(input) {
1824
+ const ctxAny = this.context;
1825
+ const principalLineage = this.ownerLineageForBinding(input.binding);
1826
+ const settingsSvc = ctxAny.get?.('settings');
1827
+ const credentialsSvc = ctxAny.get?.('credentials');
1828
+ const defaultModelSvc = ctxAny.get?.('agentDefaultModel');
1829
+ const llmSvc = ctxAny.get?.('llm');
1830
+ const prefSvc = ctxAny.get?.('assistantPreferenceLearning');
1831
+ return await buildConfigPickerSnapshot({
1832
+ operationId: input.operationId,
1833
+ issuedAt: input.issuedAt,
1834
+ expiresAt: input.expiresAt,
1835
+ bindingVersion: input.binding.version,
1836
+ sessionId: input.binding.sessionId,
1837
+ conversationKind: input.binding.conversation.kind,
1838
+ activeCategory: input.activeCategory,
1839
+ ...(input.activeProviderId === undefined ? {} : { activeProviderId: input.activeProviderId }),
1840
+ workspace: input.binding.workspace,
1841
+ preset: input.binding.agentPreset,
1842
+ principalId: externalPrincipalId(input.binding.principal),
1843
+ ...(principalLineage === undefined ? {} : { principalLineage }),
1844
+ ...(settingsSvc === undefined ? {} : { settings: settingsSvc }),
1845
+ ...(credentialsSvc === undefined ? {} : { credentials: credentialsSvc }),
1846
+ ...(defaultModelSvc === undefined ? {} : { agentDefaultModel: defaultModelSvc }),
1847
+ ...(llmSvc === undefined ? {} : { llm: llmSvc }),
1848
+ ...(prefSvc === undefined ? {} : { preferenceLearning: prefSvc }),
1849
+ ...(input.learningExplainReceipt === undefined ? {} : { learningExplainReceipt: input.learningExplainReceipt }),
1850
+ ...(input.categoryNotices === undefined ? {} : { categoryNotices: input.categoryNotices }),
1851
+ });
1852
+ }
1853
+ async buildConfigPickerForCommand(binding, envelope, activeCategory) {
1854
+ const issuedAt = Date.now();
1855
+ const explainResult = await this.dispatchLearningCommand(binding, envelope, 'explain');
1856
+ const learningExplainReceipt = typeof explainResult === 'object' ? explainResult : undefined;
1857
+ return await this.buildConfigPickerSnapshotForBinding({
1858
+ binding,
1859
+ operationId: this.configOperationId(binding.conversation, envelope.eventId),
1860
+ issuedAt,
1861
+ expiresAt: issuedAt + this.config.configPickerTtlMs,
1862
+ activeCategory,
1863
+ ...(learningExplainReceipt === undefined ? {} : { learningExplainReceipt }),
1864
+ });
1865
+ }
1866
+ async applyConversationPreferenceMutation(binding, envelope, pairs) {
1867
+ const parsed = parseT1ConversationSelections(pairs);
1868
+ if (!parsed.ok) {
1869
+ return { ok: false, message: parsed.message };
1870
+ }
1871
+ const selections = parsed.selections.map(sel => ({
1872
+ preferenceKey: sel.preferenceKey,
1873
+ candidateValue: sel.candidateValue,
1874
+ interpretationTrust: 'explicit-selection',
1875
+ }));
1876
+ const attestation = this.authorizeOwnerPreferenceFeedback(binding, envelope, selections);
1877
+ if (attestation === undefined) {
1878
+ return { ok: false, message: '偏好修改授权未通过(owner 或策略限制)' };
1879
+ }
1880
+ const events = selections.map(selection => feedbackSignalInput(binding, envelope, selection, attestation));
1881
+ const dispatchResult = await this.dispatchPreferenceFeedback(Object.freeze(events));
1882
+ if (dispatchResult === 'unavailable') {
1883
+ return { ok: false, message: '偏好学习服务(preference-learning)尚未挂载,本次偏好未写入' };
1884
+ }
1885
+ if (dispatchResult === 'unknown') {
1886
+ return { ok: false, message: '偏好写入状态未确认,请稍后重试' };
1887
+ }
1888
+ const explainResult = await this.dispatchLearningCommand(binding, envelope, 'explain');
1889
+ if (typeof explainResult === 'object') {
1890
+ if (explainResult.outcome === 'stale') {
1891
+ return {
1892
+ ok: false,
1893
+ explainReceipt: explainResult,
1894
+ message: '检测到更新的偏好控制操作,本次偏好状态未覆盖',
1895
+ };
1896
+ }
1897
+ if (!explainResult.state.administrativelyEnabled) {
1898
+ return {
1899
+ ok: false,
1900
+ explainReceipt: explainResult,
1901
+ message: '偏好学习服务当前已禁用(enabled=false),已记录但暂不会激活生效',
1902
+ };
1903
+ }
1904
+ if (explainResult.state.collectionMode === 'paused') {
1905
+ return {
1906
+ ok: true,
1907
+ explainReceipt: explainResult,
1908
+ message: '偏好学习当前处于暂停状态(/learning resume 可恢复);选择已记录,恢复后激活',
1909
+ };
1910
+ }
1911
+ const activePairs = new Set((explainResult.explanation ?? [])
1912
+ .filter(item => item.state === 'active')
1913
+ .map(item => `${item.key}\0${item.value}`));
1914
+ const allActive = selections.every(sel => activePairs.has(`${sel.preferenceKey}\0${sel.candidateValue}`));
1915
+ if (allActive) {
1916
+ return {
1917
+ ok: true,
1918
+ explainReceipt: explainResult,
1919
+ message: `对话偏好已更新并立即激活(${selections.map(s => `${s.preferenceKey}=${s.candidateValue}`).join(',')})`,
1920
+ };
1921
+ }
1922
+ return {
1923
+ ok: true,
1924
+ explainReceipt: explainResult,
1925
+ message: '已记录偏好选择;当前未立即激活(可能受 autonomousT1Enabled=false 或激活上限限制)',
1926
+ };
1927
+ }
1928
+ return { ok: true, message: '已提交对话偏好选择' };
1929
+ }
1930
+ async settleConfigAction(input) {
1931
+ this.assertActive();
1932
+ if (!/^[A-Za-z0-9][A-Za-z0-9._@:-]{0,255}$/u.test(input.operationId)
1933
+ || !/^[A-Za-z0-9][A-Za-z0-9._@:-]{0,255}$/u.test(input.callbackEventId)
1934
+ || !/^[A-Za-z0-9][A-Za-z0-9._@/-]{0,511}$/u.test(input.cardMessageId)
1935
+ || !/^[A-Za-z0-9][A-Za-z0-9._@:-]{0,255}$/u.test(input.bindingId)
1936
+ || !/^[a-f0-9]{64}$/u.test(input.expectedStateHash)
1937
+ || !Number.isSafeInteger(input.bindingVersion) || input.bindingVersion < 1
1938
+ || !Number.isSafeInteger(input.issuedAt) || input.issuedAt < 1
1939
+ || !Number.isSafeInteger(input.expiresAt) || input.expiresAt <= input.issuedAt) {
1940
+ throw new AssistantDeliveryError('missing-binding', 'config picker callback shape is invalid');
1941
+ }
1942
+ const binding = this.deliveryStore.getBinding(input.bindingId);
1943
+ const active = binding === undefined ? undefined : this.deliveryStore.getActiveBinding(binding.conversation);
1944
+ const principal = this.deliveryStore.getPrincipal(input.principal);
1945
+ if (binding?.status !== 'active' || active?.id !== binding.id
1946
+ || principal?.status !== 'active' || principal.role !== 'owner'
1947
+ || !this.ownsSession(binding.sessionId)
1948
+ || binding.version !== input.bindingVersion
1949
+ || binding.sessionId !== input.sessionId
1950
+ || binding.conversation.kind !== input.conversationKind
1951
+ || binding.conversation.chat !== input.callbackChatId
1952
+ || externalPrincipalId(binding.principal) !== externalPrincipalId(input.principal)) {
1953
+ throw new AssistantDeliveryError('missing-binding', 'config picker callback principal or chat does not own the active binding');
1954
+ }
1955
+ const record = this.deliveryStore.getConfigPickerRecord(input.operationId, input.bindingId);
1956
+ const picker = record?.intent.configPicker;
1957
+ if (record === undefined || picker === undefined
1958
+ || !['accepted', 'delivered', 'read'].includes(record.status)
1959
+ || record.providerMessageId !== input.cardMessageId
1960
+ || picker.operationId !== input.operationId
1961
+ || picker.issuedAt !== input.issuedAt
1962
+ || picker.expiresAt !== input.expiresAt
1963
+ || Date.now() >= picker.expiresAt) {
1964
+ throw new AssistantDeliveryError('missing-binding', 'config picker card is expired or unavailable');
1965
+ }
1966
+ const accessDecision = this.policy.evaluate({
1967
+ subject: { kind: 'external', id: externalPrincipalId(principal.principal) },
1968
+ action: 'ingest',
1969
+ resource: { kind: 'message', id: `config:${binding.id}` },
1970
+ context: { initiator: 'external' },
1971
+ });
1972
+ if (accessDecision.effect !== 'allow') {
1973
+ throw policyDenied(accessDecision);
1974
+ }
1975
+ if ((input.category === 'providers' || input.action === 'switch_provider' || input.ephemeralSecret !== undefined)
1976
+ && binding.conversation.kind !== 'dm') {
1977
+ return {
1978
+ ok: false,
1979
+ toastType: 'warning',
1980
+ toastMessage: '安全限制:模型 Provider 与 API Key 配置仅限在机器人私聊(DM)中操作',
1981
+ };
1982
+ }
1983
+ if (input.action === 'close') {
1984
+ return {
1985
+ ok: true,
1986
+ toastType: 'info',
1987
+ toastMessage: '配置面板已关闭',
1988
+ closed: true,
1989
+ };
1990
+ }
1991
+ if (input.action === 'switch_category' || input.action === 'switch_provider') {
1992
+ const explainReceipt = await this.readExplainReceiptForCallback(binding, input.operationId);
1993
+ const nextSnapshot = await this.buildConfigPickerSnapshotForBinding({
1994
+ binding,
1995
+ operationId: picker.operationId,
1996
+ issuedAt: picker.issuedAt,
1997
+ expiresAt: picker.expiresAt,
1998
+ activeCategory: input.category,
1999
+ ...(input.providerId === undefined ? {} : { activeProviderId: input.providerId }),
2000
+ ...(explainReceipt === undefined ? {} : { learningExplainReceipt: explainReceipt }),
2001
+ });
2002
+ return {
2003
+ ok: true,
2004
+ toastType: 'info',
2005
+ toastMessage: `已切换至「${nextSnapshot.categories.find(c => c.id === input.category)?.label ?? input.category}」`,
2006
+ configPicker: nextSnapshot,
2007
+ };
2008
+ }
2009
+ const currentExplain = input.category === 'conversation'
2010
+ ? await this.readExplainReceiptForCallback(binding, input.operationId)
2011
+ : undefined;
2012
+ const currentSnapshot = await this.buildConfigPickerSnapshotForBinding({
2013
+ binding,
2014
+ operationId: picker.operationId,
2015
+ issuedAt: picker.issuedAt,
2016
+ expiresAt: picker.expiresAt,
2017
+ activeCategory: input.category,
2018
+ ...(input.providerId === undefined ? {} : { activeProviderId: input.providerId }),
2019
+ ...(currentExplain === undefined ? {} : { learningExplainReceipt: currentExplain }),
2020
+ });
2021
+ if (currentSnapshot.stateHash !== input.expectedStateHash) {
2022
+ return {
2023
+ ok: false,
2024
+ toastType: 'warning',
2025
+ toastMessage: '配置状态已变化,已为您刷新最新视图,请核对后再提交',
2026
+ configPicker: currentSnapshot,
2027
+ notice: '检测到配置在卡片打开期间已更新,已刷新最新值;本次未写入。',
2028
+ };
2029
+ }
2030
+ const mutateDecision = this.policy.authorize({
2031
+ subject: { kind: 'external', id: externalPrincipalId(principal.principal) },
2032
+ action: 'ingest',
2033
+ resource: { kind: 'message', id: `config-mutate:${binding.id}:${input.category}` },
2034
+ context: { initiator: 'external' },
2035
+ }, { idempotencyKey: `config-mutate:${input.operationId}:${input.callbackEventId}` });
2036
+ if (mutateDecision.effect !== 'allow') {
2037
+ throw policyDenied(mutateDecision);
2038
+ }
2039
+ if (input.category === 'conversation') {
2040
+ const safeValues = input.formValues ?? {};
2041
+ const textParts = Object.entries(safeValues).map(([k, v]) => `${k}=${v}`);
2042
+ const syntheticCommandText = `/config conversation set ${textParts.join(' ')}`.trim();
2043
+ return await this.runConversationTransition(binding.conversation, async () => {
2044
+ const envelope = {
2045
+ channel: binding.conversation.channel,
2046
+ account: binding.conversation.account,
2047
+ eventId: input.callbackEventId,
2048
+ occurredAt: Date.now(),
2049
+ principal: { ...principal.principal },
2050
+ conversation: { ...binding.conversation },
2051
+ kind: 'command',
2052
+ text: syntheticCommandText,
2053
+ metadata: {
2054
+ 'config-picker-operation': picker.operationId,
2055
+ },
2056
+ };
2057
+ const claimed = this.deliveryStore.claimConfigCallbackInbox({
2058
+ envelope,
2059
+ bindingId: binding.id,
2060
+ ownerId: this.ownerId,
2061
+ leaseMs: this.config.leaseMs,
2062
+ });
2063
+ if (claimed.duplicate) {
2064
+ const explainReceipt = await this.readExplainReceiptForCallback(binding, input.operationId);
2065
+ const refreshed = await this.buildConfigPickerSnapshotForBinding({
2066
+ binding,
2067
+ operationId: picker.operationId,
2068
+ issuedAt: picker.issuedAt,
2069
+ expiresAt: picker.expiresAt,
2070
+ activeCategory: 'conversation',
2071
+ ...(explainReceipt === undefined ? {} : { learningExplainReceipt: explainReceipt }),
2072
+ });
2073
+ return {
2074
+ ok: true,
2075
+ toastType: 'info',
2076
+ toastMessage: '该偏好提交已处理',
2077
+ configPicker: refreshed,
2078
+ };
2079
+ }
2080
+ let outcome;
2081
+ try {
2082
+ const t1Values = {};
2083
+ let showProcessLogsVal;
2084
+ let unknownKey;
2085
+ for (const [key, val] of Object.entries(safeValues)) {
2086
+ if (Object.hasOwn(T1_TEXT_KEY_ALIASES, key)) {
2087
+ t1Values[key] = val;
2088
+ }
2089
+ else if (key === OWNER_CONSOLE_PROCESS_LOGS_KEY) {
2090
+ showProcessLogsVal = val;
2091
+ }
2092
+ else {
2093
+ unknownKey = key;
2094
+ break;
2095
+ }
2096
+ }
2097
+ if (unknownKey !== undefined) {
2098
+ outcome = { ok: false, message: `不支持的对话偏好字段:${unknownKey}` };
2099
+ }
2100
+ else {
2101
+ const ctxAny = this.context;
2102
+ const settingsSvc = ctxAny.get?.('settings');
2103
+ const currentShowProcessLogs = readOwnerConsoleShowProcessLogs(settingsSvc);
2104
+ const hasT1Edits = Object.keys(t1Values).length > 0;
2105
+ const normalizedShowVal = showProcessLogsVal?.trim().toLowerCase();
2106
+ const showUnchanged = currentShowProcessLogs !== undefined
2107
+ && (normalizedShowVal === String(currentShowProcessLogs)
2108
+ || (currentShowProcessLogs && (normalizedShowVal === '1' || normalizedShowVal === 'on' || normalizedShowVal === 'yes'))
2109
+ || (!currentShowProcessLogs && (normalizedShowVal === '0' || normalizedShowVal === 'off' || normalizedShowVal === 'no')));
2110
+ const shouldMutateShow = showProcessLogsVal !== undefined && (!hasT1Edits || !showUnchanged);
2111
+ if (!hasT1Edits && !shouldMutateShow) {
2112
+ outcome = { ok: false, message: '未检测到可修改的对话偏好字段' };
2113
+ }
2114
+ else {
2115
+ const convCat = currentSnapshot.categories.find(cat => cat.id === 'conversation');
2116
+ const expectedRevisions = convCat?.namespace !== undefined && convCat?.revision !== undefined
2117
+ ? { [convCat.namespace]: convCat.revision }
2118
+ : undefined;
2119
+ let preValidationError;
2120
+ if (hasT1Edits) {
2121
+ const t1Validation = parseT1ConversationSelections(t1Values);
2122
+ if (!t1Validation.ok)
2123
+ preValidationError = t1Validation.message;
2124
+ }
2125
+ if (preValidationError === undefined && shouldMutateShow && showProcessLogsVal !== undefined) {
2126
+ const showValidation = validateOwnerConsoleConversationMutation({
2127
+ values: { [OWNER_CONSOLE_PROCESS_LOGS_KEY]: showProcessLogsVal },
2128
+ ...(expectedRevisions === undefined ? {} : { expectedRevisions }),
2129
+ ...(settingsSvc === undefined ? {} : { settings: settingsSvc }),
2130
+ });
2131
+ if (!showValidation.ok)
2132
+ preValidationError = showValidation.message;
2133
+ }
2134
+ if (preValidationError !== undefined) {
2135
+ outcome = { ok: false, message: preValidationError };
2136
+ }
2137
+ else {
2138
+ const messages = [];
2139
+ let allOk = true;
2140
+ let explainReceipt;
2141
+ if (hasT1Edits) {
2142
+ const t1Res = await this.applyConversationPreferenceMutation(binding, envelope, t1Values);
2143
+ allOk = allOk && t1Res.ok;
2144
+ messages.push(t1Res.message);
2145
+ explainReceipt = t1Res.explainReceipt;
2146
+ }
2147
+ if (allOk && shouldMutateShow && showProcessLogsVal !== undefined) {
2148
+ const showRes = await applyOwnerConsoleConversationMutation({
2149
+ values: { [OWNER_CONSOLE_PROCESS_LOGS_KEY]: showProcessLogsVal },
2150
+ ...(expectedRevisions === undefined ? {} : { expectedRevisions }),
2151
+ ...(settingsSvc === undefined ? {} : { settings: settingsSvc }),
2152
+ });
2153
+ allOk = allOk && showRes.ok;
2154
+ messages.push(showRes.message);
2155
+ }
2156
+ outcome = {
2157
+ ok: allOk,
2158
+ message: messages.join(';'),
2159
+ ...(explainReceipt === undefined ? {} : { explainReceipt }),
2160
+ };
2161
+ }
2162
+ }
2163
+ }
2164
+ this.deliveryStore.finishInbox({
2165
+ inboxId: claimed.record.id,
2166
+ ownerId: this.ownerId,
2167
+ fencingToken: claimed.fencingToken,
2168
+ outcome: 'processed',
2169
+ });
2170
+ }
2171
+ catch (error) {
2172
+ try {
2173
+ this.deliveryStore.finishInbox({
2174
+ inboxId: claimed.record.id,
2175
+ ownerId: this.ownerId,
2176
+ fencingToken: claimed.fencingToken,
2177
+ outcome: 'dead_letter',
2178
+ failureCode: 'config-callback-failed',
2179
+ });
2180
+ }
2181
+ catch { }
2182
+ throw error;
2183
+ }
2184
+ const refreshed = await this.buildConfigPickerSnapshotForBinding({
2185
+ binding,
2186
+ operationId: picker.operationId,
2187
+ issuedAt: picker.issuedAt,
2188
+ expiresAt: picker.expiresAt,
2189
+ activeCategory: 'conversation',
2190
+ ...(outcome.explainReceipt === undefined ? {} : { learningExplainReceipt: outcome.explainReceipt }),
2191
+ categoryNotices: { conversation: outcome.message },
2192
+ });
2193
+ return {
2194
+ ok: outcome.ok,
2195
+ toastType: outcome.ok ? 'success' : 'warning',
2196
+ toastMessage: outcome.message,
2197
+ configPicker: refreshed,
2198
+ notice: outcome.message,
2199
+ };
2200
+ });
2201
+ }
2202
+ const ctxAny = this.context;
2203
+ const settingsSvc = ctxAny.get?.('settings');
2204
+ const credentialsSvc = ctxAny.get?.('credentials');
2205
+ const defaultModelSvc = ctxAny.get?.('agentDefaultModel');
2206
+ const outcome = await applyNonPreferenceConfigMutation({
2207
+ category: input.category,
2208
+ conversationKind: binding.conversation.kind,
2209
+ values: input.formValues ?? {},
2210
+ ...(input.ephemeralSecret === undefined ? {} : { ephemeralSecret: input.ephemeralSecret }),
2211
+ ...(input.providerId === undefined ? {} : { targetProviderId: input.providerId }),
2212
+ ...(settingsSvc === undefined ? {} : { settings: settingsSvc }),
2213
+ ...(credentialsSvc === undefined ? {} : { credentials: credentialsSvc }),
2214
+ ...(defaultModelSvc === undefined ? {} : { agentDefaultModel: defaultModelSvc }),
2215
+ });
2216
+ const safeMessage = redactConfigSecret(outcome.message, input.ephemeralSecret);
2217
+ const nextProviderId = outcome.activeProviderId ?? input.providerId;
2218
+ const refreshed = await this.buildConfigPickerSnapshotForBinding({
2219
+ binding,
2220
+ operationId: picker.operationId,
2221
+ issuedAt: picker.issuedAt,
2222
+ expiresAt: picker.expiresAt,
2223
+ activeCategory: input.category,
2224
+ ...(nextProviderId === undefined ? {} : { activeProviderId: nextProviderId }),
2225
+ categoryNotices: { [input.category]: safeMessage },
2226
+ });
2227
+ return {
2228
+ ok: outcome.ok,
2229
+ toastType: outcome.ok ? 'success' : 'warning',
2230
+ toastMessage: safeMessage,
2231
+ configPicker: refreshed,
2232
+ notice: safeMessage,
2233
+ };
2234
+ }
1771
2235
  async settlePermissionSelection(input) {
1772
2236
  this.assertActive();
1773
2237
  if (!/^[A-Za-z0-9][A-Za-z0-9._@:-]{0,255}$/u.test(input.callbackEventId)
@@ -2397,6 +2861,19 @@ export class AssistantDeliveryService extends Service {
2397
2861
  if (sink !== undefined)
2398
2862
  await sink.registration.completed(handle);
2399
2863
  }
2864
+ listSlashCommands() {
2865
+ let activeNativeCommandNames;
2866
+ try {
2867
+ const commands = this.ctx.get('commands');
2868
+ if (typeof commands?.list === 'function') {
2869
+ activeNativeCommandNames = commands.list(undefined).map(entry => entry.name);
2870
+ }
2871
+ }
2872
+ catch {
2873
+ activeNativeCommandNames = undefined;
2874
+ }
2875
+ return listLarkSlashCommandSpecs(activeNativeCommandNames === undefined ? undefined : { activeNativeCommandNames });
2876
+ }
2400
2877
  registerAdapter(adapter) {
2401
2878
  this.assertActive();
2402
2879
  return this.registry.register(adapter).then(unregister => {
@@ -7973,6 +8450,9 @@ export class AssistantDeliveryService extends Service {
7973
8450
  target: { conversation: binding.conversation, principal: binding.principal },
7974
8451
  text: input.text,
7975
8452
  format,
8453
+ ...(format !== 'config-picker' || input.configPicker === undefined
8454
+ ? {}
8455
+ : { configPicker: input.configPicker }),
7976
8456
  ...(input.modelPicker === undefined ? {} : { modelPicker: input.modelPicker }),
7977
8457
  ...(format !== 'permission-picker' || input.permissionPicker === undefined
7978
8458
  ? {}
@@ -7990,9 +8470,9 @@ export class AssistantDeliveryService extends Service {
7990
8470
  * degrade to plain text elsewhere, so a reply is never lost to a capability mismatch.
7991
8471
  */
7992
8472
  replyFormat(conversation, requested) {
7993
- if (requested === 'permission-picker') {
8473
+ if (requested === 'permission-picker' || requested === 'config-picker') {
7994
8474
  const adapter = this.registry.get(conversation.channel, conversation.account);
7995
- return adapter?.capabilities.formats.includes('permission-picker') === true ? requested : 'plain';
8475
+ return adapter?.capabilities.formats.includes(requested) === true ? requested : 'plain';
7996
8476
  }
7997
8477
  if (requested !== 'markdown')
7998
8478
  return requested;