dsh-kingdom 1.0.0 → 2.0.0

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 (144) hide show
  1. package/ASSETS_NOTICE.md +18 -2
  2. package/LICENSE +661 -661
  3. package/NOTICE +9 -9
  4. package/README.md +26 -20
  5. package/THIRD_PARTY_NOTICES.md +84 -0
  6. package/cordis.patch.yml +6 -6
  7. package/docs/V2.0-RELEASE-NOTES.md +30 -0
  8. package/docs/V2.0-USER-GUIDE.md +74 -0
  9. package/lib/adapter/dsh-backend.js +10 -6
  10. package/lib/adapter/dsh-backend.js.map +1 -1
  11. package/lib/adapter/dsh-cost.js +68 -0
  12. package/lib/adapter/dsh-cost.js.map +1 -0
  13. package/lib/adapter/dsh-session-events.js +86 -0
  14. package/lib/adapter/dsh-session-events.js.map +1 -0
  15. package/lib/adapter/dsh-usage.js +159 -0
  16. package/lib/adapter/dsh-usage.js.map +1 -0
  17. package/lib/capability/admin.js +4 -4
  18. package/lib/capability/admin.js.map +1 -1
  19. package/lib/capability/dsh-enforcement.js +19 -4
  20. package/lib/capability/dsh-enforcement.js.map +1 -1
  21. package/lib/capability/service.js +11 -0
  22. package/lib/capability/service.js.map +1 -1
  23. package/lib/capability/tool-disclosure.js +144 -0
  24. package/lib/capability/tool-disclosure.js.map +1 -0
  25. package/lib/core/binding.js +20 -18
  26. package/lib/core/binding.js.map +1 -1
  27. package/lib/core/budget.js +304 -0
  28. package/lib/core/budget.js.map +1 -0
  29. package/lib/core/collaboration.js +422 -0
  30. package/lib/core/collaboration.js.map +1 -0
  31. package/lib/core/cost.js +212 -0
  32. package/lib/core/cost.js.map +1 -0
  33. package/lib/core/db.js +124 -0
  34. package/lib/core/db.js.map +1 -1
  35. package/lib/core/governed-claim.js +46 -0
  36. package/lib/core/governed-claim.js.map +1 -0
  37. package/lib/core/governed.js +112 -7
  38. package/lib/core/governed.js.map +1 -1
  39. package/lib/core/kingdom.js +58 -56
  40. package/lib/core/kingdom.js.map +1 -1
  41. package/lib/core/owner-control.js +48 -7
  42. package/lib/core/owner-control.js.map +1 -1
  43. package/lib/core/owner-window.js +822 -0
  44. package/lib/core/owner-window.js.map +1 -0
  45. package/lib/core/task-service.js +103 -72
  46. package/lib/core/task-service.js.map +1 -1
  47. package/lib/core/territory.js +33 -11
  48. package/lib/core/territory.js.map +1 -1
  49. package/lib/core/usage.js +39 -0
  50. package/lib/core/usage.js.map +1 -0
  51. package/lib/core/workspace-admission.js +225 -0
  52. package/lib/core/workspace-admission.js.map +1 -0
  53. package/lib/dispatch/evidence.js +5 -2
  54. package/lib/dispatch/evidence.js.map +1 -1
  55. package/lib/dispatch/service.js +136 -5
  56. package/lib/dispatch/service.js.map +1 -1
  57. package/lib/gui/assets/characters/chancellor-idle.svg +67 -221
  58. package/lib/gui/assets/characters/chancellor-sleeping.svg +67 -221
  59. package/lib/gui/assets/characters/chancellor-thinking.svg +67 -221
  60. package/lib/gui/assets/characters/chancellor-working.svg +67 -221
  61. package/lib/gui/assets/characters/knight-redraw-r1-idle.svg +67 -111
  62. package/lib/gui/assets/characters/knight-redraw-r1-sleeping.svg +67 -115
  63. package/lib/gui/assets/characters/knight-redraw-r1-thinking.svg +67 -173
  64. package/lib/gui/assets/characters/knight-redraw-r1-working.svg +67 -248
  65. package/lib/gui/assets/characters/supervisor-idle.svg +67 -266
  66. package/lib/gui/assets/characters/supervisor-sleeping.svg +67 -266
  67. package/lib/gui/assets/characters/supervisor-thinking.svg +67 -266
  68. package/lib/gui/assets/characters/supervisor-working.svg +67 -266
  69. package/lib/gui/console-app.js +1964 -1927
  70. package/lib/gui/console-app.js.map +1 -1
  71. package/lib/gui/contract.js.map +1 -1
  72. package/lib/gui/control-contract.js +2 -0
  73. package/lib/gui/control-contract.js.map +1 -1
  74. package/lib/gui/local-control.js +1 -0
  75. package/lib/gui/local-control.js.map +1 -1
  76. package/lib/gui/owner-control.js +310 -0
  77. package/lib/gui/owner-control.js.map +1 -0
  78. package/lib/gui/owner-ui.js +191 -0
  79. package/lib/gui/owner-ui.js.map +1 -0
  80. package/lib/gui/server.js +4 -0
  81. package/lib/gui/server.js.map +1 -1
  82. package/lib/gui/snapshot.js +150 -15
  83. package/lib/gui/snapshot.js.map +1 -1
  84. package/lib/gui/visual-assets.js +56 -0
  85. package/lib/gui/visual-assets.js.map +1 -0
  86. package/lib/gui/visual-system.js +272 -0
  87. package/lib/gui/visual-system.js.map +1 -0
  88. package/lib/gui/workbench-ui.js +358 -0
  89. package/lib/gui/workbench-ui.js.map +1 -0
  90. package/lib/gui/workbench.js +163 -0
  91. package/lib/gui/workbench.js.map +1 -0
  92. package/lib/index.js +269 -39
  93. package/lib/index.js.map +1 -1
  94. package/lib/runner-context-broker.js +8 -2
  95. package/lib/runner-context-broker.js.map +1 -1
  96. package/lib/runtime-cost-observer.js +145 -0
  97. package/lib/runtime-cost-observer.js.map +1 -0
  98. package/lib/types/adapter/contract.d.ts +2 -0
  99. package/lib/types/adapter/dsh-backend.d.ts +2 -6
  100. package/lib/types/adapter/dsh-cost.d.ts +13 -0
  101. package/lib/types/adapter/dsh-session-events.d.ts +16 -0
  102. package/lib/types/adapter/dsh-usage.d.ts +36 -0
  103. package/lib/types/capability/dsh-enforcement.d.ts +8 -6
  104. package/lib/types/capability/service.d.ts +1 -0
  105. package/lib/types/capability/tool-disclosure.d.ts +36 -0
  106. package/lib/types/core/binding.d.ts +4 -3
  107. package/lib/types/core/budget.d.ts +81 -0
  108. package/lib/types/core/collaboration.d.ts +110 -0
  109. package/lib/types/core/cost.d.ts +99 -0
  110. package/lib/types/core/db.d.ts +21 -0
  111. package/lib/types/core/governed-claim.d.ts +7 -0
  112. package/lib/types/core/governed.d.ts +19 -1
  113. package/lib/types/core/kingdom.d.ts +3 -0
  114. package/lib/types/core/owner-control.d.ts +19 -3
  115. package/lib/types/core/owner-window.d.ts +226 -0
  116. package/lib/types/core/task-service.d.ts +36 -0
  117. package/lib/types/core/territory.d.ts +7 -0
  118. package/lib/types/core/usage.d.ts +26 -0
  119. package/lib/types/core/workspace-admission.d.ts +43 -0
  120. package/lib/types/dispatch/evidence.d.ts +2 -5
  121. package/lib/types/dispatch/service.d.ts +18 -0
  122. package/lib/types/gui/console-app.d.ts +2 -1
  123. package/lib/types/gui/contract.d.ts +176 -2
  124. package/lib/types/gui/control-contract.d.ts +1 -1
  125. package/lib/types/gui/owner-control.d.ts +45 -0
  126. package/lib/types/gui/owner-ui.d.ts +2 -0
  127. package/lib/types/gui/server.d.ts +3 -0
  128. package/lib/types/gui/snapshot.d.ts +3 -10
  129. package/lib/types/gui/visual-assets.d.ts +27 -0
  130. package/lib/types/gui/visual-system.d.ts +2 -0
  131. package/lib/types/gui/workbench-ui.d.ts +5 -0
  132. package/lib/types/gui/workbench.d.ts +33 -0
  133. package/lib/types/index.d.ts +36 -4
  134. package/lib/types/runtime-cost-observer.d.ts +22 -0
  135. package/lib/types/worker/collaboration.d.ts +35 -0
  136. package/lib/types/worker/executor.d.ts +3 -0
  137. package/lib/types/worker/governed-executor.d.ts +2 -0
  138. package/lib/worker/collaboration.js +172 -0
  139. package/lib/worker/collaboration.js.map +1 -0
  140. package/lib/worker/executor.js +5 -1
  141. package/lib/worker/executor.js.map +1 -1
  142. package/lib/worker/governed-executor.js +161 -93
  143. package/lib/worker/governed-executor.js.map +1 -1
  144. package/package.json +19 -8
@@ -0,0 +1,99 @@
1
+ import type { KingdomStore } from './db.js';
2
+ /** Provider buckets are disjoint; reasoning is already included in output. */
3
+ export interface ProviderTokenCounts {
4
+ uncachedInputTokens: number;
5
+ outputTokens: number;
6
+ totalTokens: number;
7
+ cacheReadTokens?: number;
8
+ cacheWriteTokens?: number;
9
+ reasoningTokens?: number;
10
+ routes?: readonly {
11
+ provider: string;
12
+ model: string;
13
+ }[];
14
+ }
15
+ /** Neutral source observation. It cannot change role, task, or execution authority. */
16
+ export interface RoleUsageObservation {
17
+ type: 'KingdomRoleUsage/v1';
18
+ source: 'provider-reported';
19
+ sourceUnitRef: string;
20
+ runtimeInstanceRef: string;
21
+ sessionRef: string;
22
+ bindingId: string;
23
+ roleType: 'CHANCELLOR' | 'SUPERVISOR';
24
+ taskIds: string[];
25
+ attribution: 'TASK' | 'SHARED' | 'UNATTRIBUTED';
26
+ startedAt: string;
27
+ startedLedgerSeq: number;
28
+ observationSequence: number;
29
+ status: 'IN_PROGRESS' | 'COMPLETE' | 'UNAVAILABLE';
30
+ reasonCode: string | null;
31
+ observedRequests: number;
32
+ reportedRequests: number;
33
+ usage: ProviderTokenCounts | null;
34
+ }
35
+ export interface PromptCostObservation {
36
+ type: 'KingdomPromptCost/v1';
37
+ source: 'assembly-byte-observation';
38
+ sourceUnitRef: string;
39
+ bindingId: string;
40
+ roleType: string;
41
+ toolsBefore: number;
42
+ toolsAfter: number;
43
+ toolsBytesBefore: number;
44
+ toolsBytesAfter: number;
45
+ sections: {
46
+ name: string;
47
+ bytes: number;
48
+ }[];
49
+ contexts: {
50
+ name: string;
51
+ bytes: number;
52
+ }[];
53
+ /** Assembly has no final history envelope; never substitute a zero. */
54
+ historyBytes: null;
55
+ tokenEstimate: null;
56
+ mode: 'off' | 'pilot';
57
+ reasonCode: string | null;
58
+ }
59
+ export declare function validProviderCounts(usage: ProviderTokenCounts): boolean;
60
+ export declare function recordUsageCoverageGap(store: KingdomStore, kingdomId: string, sourceUnitRef: string, reasonCode: 'ROLE_IDENTITY_AMBIGUOUS'): void;
61
+ /** Arbitrary plugin names are not trusted metadata. Only fixed public categories reach the ledger. */
62
+ export declare function safePromptPartName(value: string, index: number, type: 'section' | 'context'): string;
63
+ export declare function recordRoleUsage(store: KingdomStore, kingdomId: string, input: RoleUsageObservation): boolean;
64
+ export interface AdditionalRoleCostSummary {
65
+ scope: 'OBSERVED_GOVERNANCE_TURNS';
66
+ units: number;
67
+ completeUnits: number;
68
+ pendingUnits: number;
69
+ unknownUnits: number;
70
+ attributionGapCount: number;
71
+ observedRequests: number;
72
+ reportedRequests: number;
73
+ verifiedTokens: number | null;
74
+ byRole: {
75
+ roleType: string;
76
+ units: number;
77
+ completeUnits: number;
78
+ verifiedTokens: number | null;
79
+ }[];
80
+ sharedTokens: number | null;
81
+ unattributedTokens: number | null;
82
+ amount: null;
83
+ amountStatus: 'PRICE_NOT_CONFIGURED';
84
+ coverageNote: string;
85
+ }
86
+ /** Lost observer continuity is unknown usage, never proof a Runtime stopped. */
87
+ export declare function closeInterruptedRoleObservations(store: KingdomStore, kingdomId: string, runtimeInstanceRef: string): number;
88
+ export declare function readAdditionalRoleCost(store: KingdomStore, kingdomId: string, taskId?: string): AdditionalRoleCostSummary;
89
+ /** Add only non-Worker observations; Worker dispatch reports are already counted by budget.ts. */
90
+ export declare function readIncompleteRoleUsageSourceRefs(store: KingdomStore, kingdomId: string): string[];
91
+ /** Frozen carry-in sources preserve work already pending when the first policy was created. */
92
+ export declare function readAdditionalBudgetUsage(store: KingdomStore, kingdomId: string, sinceEventSeq: number, carriedSourceRefs?: readonly string[]): {
93
+ verifiedTokens: number;
94
+ unknownUnits: number;
95
+ pendingUnits: number;
96
+ attributionGapCount: number;
97
+ };
98
+ export declare function recordPromptCost(store: KingdomStore, kingdomId: string, input: PromptCostObservation): void;
99
+ export declare function readLatestPromptCosts(store: KingdomStore, kingdomId: string): PromptCostObservation[];
@@ -443,6 +443,12 @@ export declare class KingdomStore {
443
443
  tombstoneTerritoryRow(territoryId: string, reason: string | null): void;
444
444
  /** v0.7.0(M2):设置 Territory 主理 Supervisor(scope relation;NULL=未指派=fail-closed)。 */
445
445
  updateTerritorySupervisor(territoryId: string, supervisorBindingId: string | null): void;
446
+ updateTerritoryMetadata(territoryId: string, name: string, summary: string | null): void;
447
+ getEventById(eventId: string): EventRow | null;
448
+ /** Global append cursor; callers predicting a receipt sequence must hold the write transaction. */
449
+ eventSequence(): number;
450
+ /** Owner topology guards include RECOVERING and unknown future nonterminal states. */
451
+ listUnsettledOwnerExecutions(kingdomId: string): ExecutionRow[];
446
452
  insertTaskAssignment(row: TaskAssignmentRow): TaskAssignmentRow;
447
453
  /** 当前 active assignment(partial unique index 保证至多一条)。 */
448
454
  getActiveAssignmentForTask(taskId: string): TaskAssignmentRow | null;
@@ -511,6 +517,12 @@ export declare class KingdomStore {
511
517
  * GUI 比较 revision 就知道要不要重绘,不必 diff 整个 snapshot。
512
518
  */
513
519
  revision(kingdomId: string): number;
520
+ /** Observations and future admission/window policy cannot change an in-flight Runner relation. */
521
+ runnerContextRevision(kingdomId: string, scope?: {
522
+ taskId: string;
523
+ workerBindingId: string;
524
+ sessionRef: string;
525
+ }): number;
514
526
  /**
515
527
  * v0.7.0(M2):外层事务包装——HANDOFF 等**原子治理操作**(多步写 + 事件)整体提交/回滚。
516
528
  * appendEvent 的内层 BEGIN 在事务中会抛错,由 appendEvent 的嵌套容忍逻辑接管(见下)。
@@ -556,6 +568,15 @@ export declare class KingdomStore {
556
568
  }): TaskRow;
557
569
  listWorkerResults(taskId: string): WorkerResultRow[];
558
570
  latestWorkerResult(taskId: string): WorkerResultRow | null;
571
+ /** Exact task/attempt lookup; unrelated kingdom activity cannot hide the reviewed attempt. */
572
+ latestTaskReworkEvent(kingdomId: string, taskId: string, reviewedAttemptNo: number): EventRow | null;
573
+ listDispatchUsageEvents(dispatchId: string): EventRow[];
574
+ /** Complete exact budget ledger; display event windows must never be used as accounting history. */
575
+ listBudgetEvents(kingdomId: string): EventRow[];
576
+ listWorkspaceAdmissionEvents(kingdomId: string): EventRow[];
577
+ listRuntimeCostEvents(kingdomId: string): EventRow[];
578
+ listActorEventsSince(kingdomId: string, actorId: string, afterSeq: number): EventRow[];
579
+ getLatestRuntimeRoleUsageEvent(kingdomId: string, sourceUnitRef: string): EventRow | null;
559
580
  /** 已落库的最大 attempt_no;无结果时为 0。下一次尝试 = 本值 + 1。 */
560
581
  maxAttemptNo(taskId: string): number;
561
582
  /**
@@ -0,0 +1,7 @@
1
+ import type { KingdomStore } from './db.js';
2
+ /** One terminal dispatch produces one Claim. Runtime completion never accepts a task. */
3
+ export declare function submitGovernedClaim(store: KingdomStore, dispatchId: string, summary: string): {
4
+ created: boolean;
5
+ summary: string;
6
+ outcome: string;
7
+ };
@@ -1,4 +1,7 @@
1
1
  import { KingdomStore, type AffinityRow, type LeaseRow, type CapabilityDecisionRow, type DispatchRecordRow, type ExecutionRow, type EventRow, StaleStateError } from './db.js';
2
+ import { type BudgetAdmissionHandle } from './budget.js';
3
+ import { type WorkspaceAdmissionHandle } from './workspace-admission.js';
4
+ import { type CollaborationReadiness } from './collaboration.js';
2
5
  /** 完整 Runtime Session identity(M3-S1 冻结:(runtime_type, runtime_instance_ref, session_ref))。 */
3
6
  export interface SessionIdentity {
4
7
  runtimeType: string;
@@ -13,7 +16,7 @@ export declare class GovernedApiError extends Error {
13
16
  export declare class SchemaV4NotMigratedError extends GovernedApiError {
14
17
  constructor();
15
18
  }
16
- export type RunnerContextPhase = 'OPEN' | 'ACQUIRED' | 'BOUND' | 'TERMINAL' | 'RECOVERING' | 'RELEASED' | 'INVALID';
19
+ export type RunnerContextPhase = 'OPEN' | 'ACQUIRED' | 'BOUND' | 'TERMINAL' | 'RECOVERING' | 'RECOVERY_TERMINAL' | 'RELEASED' | 'INVALID';
17
20
  export type RunnerContextErrorCode = 'RELATION_MISSING' | 'RELATION_MISMATCH' | 'INVALID_HANDLE' | 'INVALID_VERSION' | 'STALE_VERSION' | 'INVALID_ORDER' | 'RECOVERING' | 'RELEASED';
18
21
  export declare class RunnerContextError extends GovernedApiError {
19
22
  readonly code: RunnerContextErrorCode;
@@ -94,6 +97,18 @@ export declare class RunnerContextPort {
94
97
  */
95
98
  correlateRuntimeExecution<T>(handle: RunnerContextHandle, version: RunnerContextVersion, runtimeExecutionRef: string, action: (context: RunnerContextActionContext) => T): RunnerContextMutationResult<T>;
96
99
  observeTerminal<T>(handle: RunnerContextHandle, version: RunnerContextVersion, action: (context: RunnerContextActionContext) => T): RunnerContextMutationResult<T>;
100
+ /** Observation timeout retains this original capability; the factory still rejects RECOVERING. */
101
+ deferRecovery(handle: RunnerContextHandle, version: RunnerContextVersion): RunnerContextMutationResult<ReturnType<typeof markGovernedDispatchRecovering>>;
102
+ /** Only the original deferred port can consume late evidence; no recovered factory or new Runner. */
103
+ checkRecovery(handle: RunnerContextHandle, version: RunnerContextVersion): RunnerContextView;
104
+ recoverTerminal(handle: RunnerContextHandle, version: RunnerContextVersion, input: TerminalEvidenceInput & {
105
+ runtimeExecutionRef: string;
106
+ }): RunnerContextMutationResult<{
107
+ dispatch: DispatchRecordRow;
108
+ execution: ExecutionRow;
109
+ lease: LeaseRow;
110
+ }>;
111
+ settleRecovery<T>(handle: RunnerContextHandle, version: RunnerContextVersion, action: (context: RunnerContextActionContext) => T): RunnerContextMutationResult<T>;
97
112
  settle<T>(handle: RunnerContextHandle, version: RunnerContextVersion, action: (context: RunnerContextActionContext) => T): RunnerContextMutationResult<T>;
98
113
  }
99
114
  /**
@@ -224,6 +239,9 @@ export interface PrepareGovernedDispatchInput {
224
239
  dispatchId?: string;
225
240
  preparedAt?: string;
226
241
  detail?: string | null;
242
+ budgetAdmission?: BudgetAdmissionHandle;
243
+ workspaceAdmission?: WorkspaceAdmissionHandle;
244
+ collaboration?: CollaborationReadiness | null;
227
245
  }
228
246
  export interface PreparedGovernedDispatchRows {
229
247
  execution: ExecutionRow;
@@ -1,4 +1,5 @@
1
1
  import { KingdomStore } from './db.js';
2
+ import { type OwnerEventSource } from './owner-control.js';
2
3
  export interface InitResult {
3
4
  action: 'initialized' | 'attached';
4
5
  kingdomId: string;
@@ -38,3 +39,5 @@ export declare class KingdomManager {
38
39
  rescan(): InitResult;
39
40
  close(): void;
40
41
  }
42
+ /** Synchronous fact writer shared by direct init and the Owner receipt transaction. */
43
+ export declare function initializeKingdomFacts(store: KingdomStore, kingdomName: string, ownerName: string, source?: OwnerEventSource): InitResult;
@@ -9,17 +9,33 @@
9
9
  import type { KingdomStore, RoleBindingRow } from './db.js';
10
10
  import type { AdminAuth } from './binding.js';
11
11
  declare const OWNER_CONTROL_MARKER: unique symbol;
12
+ export interface OwnerEventSource {
13
+ source_channel: 'LOCAL_DIRECT_SLASH' | 'LOCAL_OWNER_GUI';
14
+ authorization_source?: 'LOCAL_DIRECT_SLASH';
15
+ decision_id?: string;
16
+ operation_id?: string;
17
+ }
18
+ export interface OwnerOperationMatch {
19
+ operation: string;
20
+ input: unknown;
21
+ }
22
+ /** Stable JSON for exact, immutable operation matching. Undefined follows JSON semantics. */
23
+ export declare function ownerInputHash(input: unknown): string;
12
24
  export interface OwnerControlCapability {
13
25
  readonly [OWNER_CONTROL_MARKER]: true;
14
26
  }
15
27
  /** Mint a capability for the direct local Slash handler only. */
16
28
  export declare function issueOwnerControlCapability(): OwnerControlCapability;
17
29
  export declare function isOwnerControlCapability(value: unknown): value is OwnerControlCapability;
30
+ /** Internal controller seam; requires the original direct capability, never HTTP data. */
31
+ export declare function issueOwnerOperationCapability(authority: OwnerControlCapability, store: KingdomStore, kingdomId: string, match: OwnerOperationMatch, source: OwnerEventSource): OwnerControlCapability;
32
+ export declare function revokeOwnerOperationCapability(capability: OwnerControlCapability): void;
18
33
  export interface OwnerControlCheck {
19
34
  ok: true;
20
35
  owner: RoleBindingRow | null;
21
36
  ownerId: string;
22
- sourceChannel: 'LOCAL_DIRECT_SLASH';
37
+ sourceChannel: 'LOCAL_DIRECT_SLASH' | 'LOCAL_OWNER_GUI';
38
+ eventSource: OwnerEventSource;
23
39
  }
24
40
  export interface OwnerControlFailure {
25
41
  ok: false;
@@ -30,8 +46,8 @@ export interface OwnerControlFailure {
30
46
  * OWNER.session_id and all caller/session fields; the only authority input is
31
47
  * the opaque capability minted by the direct Slash adapter.
32
48
  */
33
- export declare function requireOwnerControl(store: KingdomStore, kingdomId: string, capability: unknown): OwnerControlCheck | OwnerControlFailure;
49
+ export declare function requireOwnerControl(store: KingdomStore, kingdomId: string, capability: unknown, match?: OwnerOperationMatch): OwnerControlCheck | OwnerControlFailure;
34
50
  /** Convert the direct capability into the shared Core admin input. */
35
51
  export declare function ownerControlAuth(capability: OwnerControlCapability): AdminAuth;
36
- export declare function ownerEventPayload(operation: string, fields?: Record<string, unknown>): Record<string, unknown>;
52
+ export declare function ownerEventPayload(operation: string, fields?: Record<string, unknown>, source?: OwnerEventSource): Record<string, unknown>;
37
53
  export {};
@@ -0,0 +1,226 @@
1
+ import type { KingdomStore } from './db.js';
2
+ import { type ExecutionProfileV1 } from './binding.js';
3
+ import { type OwnerControlCapability } from './owner-control.js';
4
+ import { type BudgetPolicyParameters } from './budget.js';
5
+ import { type PlanAdoptionParameters, type CollaborationPlanView } from './collaboration.js';
6
+ export declare const OWNER_MUTATION_ACTIONS: readonly ["init", "territory.create", "territory.update", "territory.supervisor", "role.bind", "role.session", "ceiling", "execution-profile", "budget.policy", "plan.adopt"];
7
+ export type OwnerMutationAction = typeof OWNER_MUTATION_ACTIONS[number];
8
+ export type OwnerManagedRole = 'CHANCELLOR' | 'SUPERVISOR' | 'WORKER';
9
+ export interface OwnerDecisionScope {
10
+ kingdomWide: boolean;
11
+ territoryIds: string[];
12
+ bindingIds: string[];
13
+ roleTypes: OwnerManagedRole[];
14
+ targetSessionIds: string[];
15
+ workspaceRoots: string[];
16
+ }
17
+ export interface OwnerDecisionInput {
18
+ kingdomId: string | null;
19
+ actions: OwnerMutationAction[];
20
+ scope: OwnerDecisionScope;
21
+ ttlMs: number;
22
+ }
23
+ declare const OWNER_DECISION_HANDLE: unique symbol;
24
+ export interface OwnerDecisionHandle {
25
+ readonly [OWNER_DECISION_HANDLE]: true;
26
+ }
27
+ export interface OwnerDecisionView {
28
+ decisionId: string;
29
+ kingdomId: string | null;
30
+ ownerId: string | null;
31
+ actions: OwnerMutationAction[];
32
+ scope: OwnerDecisionScope;
33
+ createdAt: string;
34
+ expiresAt: string;
35
+ state: 'ACTIVE' | 'EXPIRED' | 'REVOKED' | 'CONSUMED';
36
+ }
37
+ export interface OwnerValidationFailure {
38
+ ok: false;
39
+ code: string;
40
+ message: string;
41
+ }
42
+ export type OwnerValidationResult = {
43
+ ok: true;
44
+ } | OwnerValidationFailure;
45
+ export interface OwnerSessionValidationInput {
46
+ kingdomId: string;
47
+ roleType: 'CHANCELLOR' | 'SUPERVISOR';
48
+ bindingId: string | null;
49
+ sessionId: string;
50
+ signal: AbortSignal;
51
+ }
52
+ export interface OwnerProfileValidationInput {
53
+ kingdomId: string;
54
+ bindingId: string;
55
+ roleType: OwnerManagedRole;
56
+ profile: Readonly<ExecutionProfileV1> | null;
57
+ signal: AbortSignal;
58
+ }
59
+ export interface OwnerRuntimeSessionChoice {
60
+ id: string;
61
+ label: string;
62
+ }
63
+ export interface OwnerDecisionControllerOptions {
64
+ now?: () => number;
65
+ validationTimeoutMs?: number;
66
+ validateTargetSession: (input: OwnerSessionValidationInput) => Promise<OwnerValidationResult>;
67
+ validateExecutionProfile: (input: OwnerProfileValidationInput) => Promise<OwnerValidationResult>;
68
+ listTargetSessions: (input: {
69
+ sessionIds: readonly string[];
70
+ signal: AbortSignal;
71
+ }) => Promise<readonly OwnerRuntimeSessionChoice[]>;
72
+ }
73
+ export interface OwnerOperationCatalog {
74
+ plans?: CollaborationPlanView[];
75
+ territories: {
76
+ id: string;
77
+ name: string;
78
+ }[];
79
+ bindings: {
80
+ id: string;
81
+ roleType: string;
82
+ roleName: string;
83
+ }[];
84
+ runtimeSessions: OwnerRuntimeSessionChoice[];
85
+ workspaceRoots: string[];
86
+ }
87
+ export type OwnerOperationInput = {
88
+ action: 'init';
89
+ parameters: {
90
+ kingdom_name: string;
91
+ owner_name: string;
92
+ };
93
+ } | {
94
+ action: 'territory.create';
95
+ parameters: {
96
+ name: string;
97
+ workspace_path: string;
98
+ summary?: string | null;
99
+ };
100
+ } | {
101
+ action: 'territory.update';
102
+ parameters: {
103
+ territory_id: string;
104
+ name?: string;
105
+ summary?: string | null;
106
+ };
107
+ } | {
108
+ action: 'territory.supervisor';
109
+ parameters: {
110
+ territory_id: string;
111
+ supervisor_binding_id: string;
112
+ };
113
+ } | {
114
+ action: 'role.bind';
115
+ parameters: {
116
+ role_type: OwnerManagedRole;
117
+ role_name: string;
118
+ session_id?: string | null;
119
+ };
120
+ } | {
121
+ action: 'role.session';
122
+ parameters: {
123
+ binding_id: string;
124
+ session_id: string;
125
+ };
126
+ } | {
127
+ action: 'ceiling';
128
+ parameters: {
129
+ ceiling: Record<string, boolean>;
130
+ };
131
+ } | {
132
+ action: 'execution-profile';
133
+ parameters: {
134
+ binding_id: string;
135
+ profile: ExecutionProfileV1 | null;
136
+ };
137
+ } | {
138
+ action: 'budget.policy';
139
+ parameters: BudgetPolicyParameters;
140
+ } | {
141
+ action: 'plan.adopt';
142
+ parameters: PlanAdoptionParameters;
143
+ };
144
+ export interface OwnerOperationPreview {
145
+ prepareId: string;
146
+ operationId: string;
147
+ decisionId: string;
148
+ action: OwnerMutationAction;
149
+ summary: string;
150
+ changes: {
151
+ label: string;
152
+ before: string | null;
153
+ after: string | null;
154
+ }[];
155
+ affected: {
156
+ territoryIds: string[];
157
+ bindingIds: string[];
158
+ };
159
+ createdAt: string;
160
+ expiresAt: string;
161
+ }
162
+ export interface OwnerOperationReceipt {
163
+ type: 'KingdomOwnerOperationReceipt/v1';
164
+ operationId: string;
165
+ prepareId: string;
166
+ decisionId: string;
167
+ kingdomId: string;
168
+ ownerId: string;
169
+ action: OwnerMutationAction;
170
+ inputHash: string;
171
+ status: 'APPLIED';
172
+ target: {
173
+ type: 'kingdom' | 'territory' | 'binding' | 'collaboration-plan';
174
+ id: string;
175
+ };
176
+ receiptSeq: number;
177
+ appliedAt: string;
178
+ message: string;
179
+ }
180
+ export declare class OwnerOperationError extends Error {
181
+ readonly code: string;
182
+ constructor(code: string, message: string);
183
+ }
184
+ /** Trusted-local decision registry. Public IDs and JSON views never confer authority. */
185
+ export declare class OwnerDecisionController {
186
+ private readonly store;
187
+ private readonly options;
188
+ private readonly decisions;
189
+ private readonly now;
190
+ private readonly timeout;
191
+ private disposed;
192
+ constructor(store: KingdomStore, options: OwnerDecisionControllerOptions);
193
+ activate(capability: OwnerControlCapability, input: OwnerDecisionInput): {
194
+ handle: OwnerDecisionHandle;
195
+ decision: OwnerDecisionView;
196
+ };
197
+ inspect(handle: OwnerDecisionHandle): OwnerDecisionView | null;
198
+ catalog(handle: OwnerDecisionHandle): Promise<OwnerOperationCatalog>;
199
+ prepare(handle: OwnerDecisionHandle, raw: OwnerOperationInput, options?: {
200
+ signal?: AbortSignal;
201
+ }): Promise<OwnerOperationPreview>;
202
+ commit(handle: OwnerDecisionHandle, input: {
203
+ prepareId: string;
204
+ operationId: string;
205
+ }, options?: {
206
+ signal?: AbortSignal;
207
+ }): Promise<OwnerOperationReceipt>;
208
+ receipt(handle: OwnerDecisionHandle, operationId: string): OwnerOperationReceipt | null;
209
+ revoke(handle: OwnerDecisionHandle): OwnerDecisionView;
210
+ dispose(): void;
211
+ private expire;
212
+ private invalidate;
213
+ private active;
214
+ private assertActive;
215
+ private observe;
216
+ private validate;
217
+ private context;
218
+ private guardUnsettled;
219
+ private changes;
220
+ private apply;
221
+ /** Synchronous closed dispatcher: no callback or transport receives an administration capability. */
222
+ private mutate;
223
+ private event;
224
+ private receiptEventId;
225
+ }
226
+ export {};
@@ -10,6 +10,42 @@ export interface CommandContext {
10
10
  principal?: Principal;
11
11
  auth: AuthView;
12
12
  }
13
+ /**
14
+ * 角色校验。
15
+ *
16
+ * `declarative`(Phase 1/2 延续):只确认王国里存在该角色的 binding,
17
+ * **不验证调用者就是该角色** —— 这是本地可信演示权限,
18
+ * snapshot 的 `auth.trustLevel` 会如实报成 `local-demo`,GUI 必须显著标注。
19
+ *
20
+ * `session-bound`:额外要求调用方 session 与 binding.session_id 一致;
21
+ * binding 未绑定 session 时**拒绝**(无法验证就不放行,不猜)。
22
+ */
23
+ export declare function requireRole(store: KingdomStore, ctx: CommandContext, roleType: string): {
24
+ ok: true;
25
+ binding: RoleBindingRow;
26
+ } | {
27
+ ok: false;
28
+ code: KingdomErrorCode;
29
+ message: string;
30
+ };
31
+ /**
32
+ * Resolve the exact ACTIVE Supervisor named by the Task Territory.
33
+ *
34
+ * Session-bound callers must prove that the named binding belongs to their
35
+ * Runtime session. A caller that proves a different ACTIVE Supervisor role is
36
+ * out of scope; a caller that proves no ACTIVE Supervisor role is unauthorized.
37
+ * Declarative/local-demo keeps its historical low-trust behavior, but still
38
+ * resolves the Territory pointer instead of attributing writes to an arbitrary
39
+ * first Supervisor row.
40
+ */
41
+ export declare function resolveTaskSupervisor(store: KingdomStore, ctx: CommandContext, task: TaskRow): {
42
+ ok: true;
43
+ binding: RoleBindingRow;
44
+ } | {
45
+ ok: false;
46
+ code: KingdomErrorCode;
47
+ message: string;
48
+ };
13
49
  /** 公共 governed start 只能由真实 session-bound Supervisor 进入执行器前的授权门。 */
14
50
  export declare function resolveGovernedStartSupervisor(store: KingdomStore, ctx: CommandContext, taskId: string): {
15
51
  ok: true;
@@ -17,6 +17,13 @@ export interface DeleteTerritoryInput {
17
17
  }
18
18
  export declare function createTerritory(store: KingdomStore, input: CreateTerritoryInput, auth?: AdminAuth): string;
19
19
  export declare function listTerritories(store: KingdomStore, kingdomId: string): string;
20
+ /** Metadata-only update. Workspace paths and identity are immutable through this operation. */
21
+ export declare function updateTerritory(store: KingdomStore, input: {
22
+ kingdomId: string;
23
+ territoryId: string;
24
+ name?: string;
25
+ summary?: string | null;
26
+ }, auth?: AdminAuth): string;
20
27
  /**
21
28
  * v0.7.0(M2):设置 Territory 主理 Supervisor(Topology Administration Plane)。
22
29
  * - 仅 direct Owner Control capability 可执行(requireAdmin → requireOwnerControl);
@@ -0,0 +1,26 @@
1
+ import type { KingdomStore } from './db.js';
2
+ import type { DshDispatchUsageObservation } from '../adapter/dsh-usage.js';
3
+ export interface DispatchUsageView {
4
+ type: 'KingdomDispatchUsage/v1';
5
+ dispatchId: string;
6
+ taskId: string;
7
+ attemptNo: number;
8
+ source: 'provider-reported';
9
+ status: 'COMPLETE' | 'PARTIAL' | 'UNAVAILABLE';
10
+ reasonCode: string | null;
11
+ observedRequests: number;
12
+ reportedRequests: number;
13
+ turn: number | null;
14
+ throughSeq: number | null;
15
+ usage: {
16
+ uncachedInputTokens: number;
17
+ outputTokens: number;
18
+ totalTokens: number;
19
+ cacheReadTokens?: number;
20
+ cacheWriteTokens?: number;
21
+ reasoningTokens?: number;
22
+ } | null;
23
+ }
24
+ export declare function readDispatchUsage(store: KingdomStore, dispatchId: string): DispatchUsageView | null;
25
+ /** Runtime usage is a separate observation, never terminal/cleanup or task governance evidence. */
26
+ export declare function recordDispatchUsage(store: KingdomStore, dispatchId: string, observed: DshDispatchUsageObservation): void;
@@ -0,0 +1,43 @@
1
+ import type { KingdomStore } from './db.js';
2
+ export type WorkspaceAccess = 'READ_ONLY' | 'WRITE';
3
+ export interface WorkspaceAdmissionInput {
4
+ kingdomId: string;
5
+ taskId: string;
6
+ attemptNo: number;
7
+ workerBindingId: string;
8
+ workspacePath: string;
9
+ access: WorkspaceAccess;
10
+ }
11
+ declare const WORKSPACE_HANDLE: unique symbol;
12
+ export interface WorkspaceAdmissionHandle {
13
+ readonly [WORKSPACE_HANDLE]: true;
14
+ }
15
+ export declare class WorkspaceAdmissionError extends Error {
16
+ readonly code: string;
17
+ constructor(code: string, message: string);
18
+ }
19
+ /** Resolve existing aliases. A missing directory is rechecked again before dispatch. */
20
+ export declare function canonicalWorkspaceKey(path: string): string;
21
+ export declare function workspaceKeysOverlap(a: string, b: string): boolean;
22
+ /** Both entry points check occupancy inside their fact-creation transaction. Unknown paths overlap conservatively. */
23
+ export declare function assertWorkspaceAvailable(store: KingdomStore, kingdomId: string, key: string | null, access: WorkspaceAccess): void;
24
+ /** Called within the same admission transaction as plan checks and budget reservation. */
25
+ export declare function reserveWorkspaceAdmission(store: KingdomStore, input: WorkspaceAdmissionInput): WorkspaceAdmissionHandle;
26
+ export declare function bindWorkspaceAdmissionInTransaction(store: KingdomStore, handle: WorkspaceAdmissionHandle | undefined, input: {
27
+ kingdomId: string;
28
+ taskId: string;
29
+ attemptNo: number;
30
+ workerBindingId: string;
31
+ dispatchId: string;
32
+ leaseId: string;
33
+ }): void;
34
+ export declare function cancelWorkspaceAdmissionIfSafe(store: KingdomStore, handle: WorkspaceAdmissionHandle): boolean;
35
+ export declare function finishWorkspaceAdmissionInvocation(handle: WorkspaceAdmissionHandle): void;
36
+ export declare function readWorkspaceReservations(store: KingdomStore, kingdomId: string): {
37
+ taskId: string;
38
+ attemptNo: number;
39
+ access: WorkspaceAccess;
40
+ state: string;
41
+ recovery: boolean;
42
+ }[];
43
+ export {};
@@ -7,6 +7,7 @@
7
7
  * - G12 Foreign/Unmanaged Dispatch 检测:active dispatch 期间出现**非本次 dispatch 的
8
8
  * user 消息** → 标记 untrusted(禁止 settle/release 并声称可信)。
9
9
  */
10
+ import { type DshSessionEventSource } from '../adapter/dsh-session-events.js';
10
11
  /**
11
12
  * turn/end reason → 已知终态 outcome 映射(Owner FINAL REAL-DSH VALIDATION WINDOW · 不改 Schema):
12
13
  * completed(+assistant) → COMPLETED;aborted → ABORTED;blocked/error/max-tokens → FAILED;
@@ -31,11 +32,7 @@ export interface DispatchEvidence {
31
32
  /** 判定为 TERMINAL 的可信理由(turn completed + assistant 消息)。 */
32
33
  terminalReason: string | null;
33
34
  }
34
- export interface SessionEventsLike {
35
- events: readonly {
36
- type: string;
37
- data?: Record<string, unknown>;
38
- }[];
35
+ export interface SessionEventsLike extends DshSessionEventSource {
39
36
  }
40
37
  /**
41
38
  * 重建一次 dispatch 的执行证据。
@@ -13,7 +13,11 @@
13
13
  */
14
14
  import type { KingdomStore, ExecutionRow, DispatchRecordRow, LeaseRow, CapabilityDecisionRow } from '../core/db.js';
15
15
  import type { RuntimeAdapter, RuntimeTrustFence, RuntimeTrustFenceExpectation, SessionHandle, DispatchReceipt } from '../adapter/contract.js';
16
+ import type { BudgetAdmissionHandle } from '../core/budget.js';
17
+ import type { WorkspaceAdmissionHandle } from '../core/workspace-admission.js';
18
+ import type { CollaborationReadiness } from '../core/collaboration.js';
16
19
  export interface GovernedDispatchInput {
20
+ stillAuthorized?: () => boolean;
17
21
  store: KingdomStore;
18
22
  adapter: RuntimeAdapter;
19
23
  kingdomId: string;
@@ -29,6 +33,9 @@ export interface GovernedDispatchInput {
29
33
  requestSnapshot: string;
30
34
  inputRefJson: string;
31
35
  payloadHash: string;
36
+ budgetAdmission?: BudgetAdmissionHandle;
37
+ workspaceAdmission?: WorkspaceAdmissionHandle;
38
+ collaboration?: CollaborationReadiness | null;
32
39
  /** 终端等待选项(测试可调小)。 */
33
40
  pollIntervalMs?: number;
34
41
  maxPolls?: number;
@@ -74,6 +81,17 @@ export type CleanupReceipt = {
74
81
  };
75
82
  /** Keep adapter evidence and settlement reasons bounded before persistence. */
76
83
  export declare const MAX_CLEANUP_EVIDENCE_LENGTH = 16384;
84
+ export interface GovernedReconcileResult {
85
+ status: 'WAIT' | 'RECOVERING' | 'TERMINAL';
86
+ reason: string;
87
+ dispatchId: string;
88
+ cleanupReceipt?: CleanupReceipt;
89
+ summary?: string;
90
+ }
91
+ /** Plugin teardown drops process evidence, never releases a governance Lease. */
92
+ export declare function discardGovernedRecoveryContexts(store: KingdomStore): void;
93
+ /** Explicit, single-flight observation of an existing original dispatch; never calls dispatch/materialize. */
94
+ export declare function reconcileGovernedDispatch(store: KingdomStore, dispatchId: string, stillAuthorized: () => boolean): Promise<GovernedReconcileResult>;
77
95
  /**
78
96
  * 受治理派发(TX-3..TX-5):
79
97
  * 1. Execution + Intent(同一事务,COMMIT POINT)→ 2. dispatch(commit 之后)→