@agimon-ai/po-task 0.0.0-alpha.10 → 0.0.0-alpha.101

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 (93) hide show
  1. package/LICENSE +149 -21
  2. package/README.md +12 -2
  3. package/dist/apiContracts.cjs +1 -0
  4. package/dist/apiContracts.cjs.map +1 -1
  5. package/dist/apiContracts.mjs +1 -0
  6. package/dist/apiContracts.mjs.map +1 -1
  7. package/dist/{delegation-Dsqf7fUM.mjs → delegation-5TOl_dEq.mjs} +4 -3
  8. package/dist/delegation-5TOl_dEq.mjs.map +1 -0
  9. package/dist/{delegation-frvEXhIz.cjs → delegation-BJtAUTVg.cjs} +4 -3
  10. package/dist/delegation-BJtAUTVg.cjs.map +1 -0
  11. package/dist/delegationManager.cjs +1 -1
  12. package/dist/delegationManager.d.mts +1 -1
  13. package/dist/delegationManager.mjs +1 -1
  14. package/dist/extensions/mcp.cjs +60 -61
  15. package/dist/extensions/mcp.cjs.map +1 -1
  16. package/dist/extensions/mcp.mjs +60 -61
  17. package/dist/extensions/mcp.mjs.map +1 -1
  18. package/dist/extensions/native.mjs +420 -315
  19. package/dist/extensions/native.mjs.map +1 -1
  20. package/dist/extensions/server.cjs +398 -136
  21. package/dist/extensions/server.cjs.map +1 -1
  22. package/dist/extensions/server.d.mts +2 -2
  23. package/dist/extensions/server.d.mts.map +1 -1
  24. package/dist/extensions/server.mjs +397 -135
  25. package/dist/extensions/server.mjs.map +1 -1
  26. package/dist/extensions/web.mjs +254 -206
  27. package/dist/extensions/web.mjs.map +1 -1
  28. package/dist/{index-DlmXKyhQ.d.mts → index-CdJx5tdI.d.mts} +2 -2
  29. package/dist/{index-DlmXKyhQ.d.mts.map → index-CdJx5tdI.d.mts.map} +1 -1
  30. package/dist/{index-B1JPJdpZ.d.mts → index-DrE00rrP.d.mts} +3 -3
  31. package/dist/{index-B1JPJdpZ.d.mts.map → index-DrE00rrP.d.mts.map} +1 -1
  32. package/dist/{index-qQGWsPum.d.mts → index-DuT-Lbxy.d.mts} +2 -3
  33. package/dist/index-DuT-Lbxy.d.mts.map +1 -0
  34. package/dist/{index-CUWCvh-E.d.mts → index-nx0ueNkm.d.mts} +2 -2
  35. package/dist/{index-CUWCvh-E.d.mts.map → index-nx0ueNkm.d.mts.map} +1 -1
  36. package/dist/{index-B9QNwUBr.d.mts → index-sahNy7Hg.d.mts} +3 -3
  37. package/dist/{index-B9QNwUBr.d.mts.map → index-sahNy7Hg.d.mts.map} +1 -1
  38. package/dist/{index-CA4Opp4r.d.mts → index-tAu1TIyi.d.mts} +4 -6
  39. package/dist/index-tAu1TIyi.d.mts.map +1 -0
  40. package/dist/index.cjs +3 -5
  41. package/dist/index.d.mts +10 -10
  42. package/dist/index.mjs +4 -4
  43. package/dist/{logSinkTelemetry-BhbKdn-x.mjs → logSinkTelemetry-3GMazFYa.mjs} +2 -2
  44. package/dist/logSinkTelemetry-3GMazFYa.mjs.map +1 -0
  45. package/dist/{logSinkTelemetry-BGb8WQBz.cjs → logSinkTelemetry-DhzIQMsV.cjs} +3 -3
  46. package/dist/logSinkTelemetry-DhzIQMsV.cjs.map +1 -0
  47. package/dist/logSinkTelemetry.cjs +1 -1
  48. package/dist/logSinkTelemetry.d.mts +1 -1
  49. package/dist/logSinkTelemetry.mjs +1 -1
  50. package/dist/{paths-P-XvOUuH.cjs → paths-CWVDY8Yd.cjs} +12 -78
  51. package/dist/paths-CWVDY8Yd.cjs.map +1 -0
  52. package/dist/{paths-DajceJig.mjs → paths-CjATVpi8.mjs} +12 -66
  53. package/dist/paths-CjATVpi8.mjs.map +1 -0
  54. package/dist/storeInvariants.d.mts +1 -1
  55. package/dist/storePaths.cjs +1 -3
  56. package/dist/storePaths.d.mts +2 -2
  57. package/dist/storePaths.mjs +1 -1
  58. package/dist/storeReconcile.d.mts +1 -1
  59. package/dist/storeReducer.d.mts +1 -1
  60. package/dist/storeTaskGraph.d.mts +1 -1
  61. package/dist/storeTaskStore.cjs +1 -1
  62. package/dist/storeTaskStore.d.mts +1 -1
  63. package/dist/storeTaskStore.mjs +1 -1
  64. package/dist/storeTypes.d.mts +1 -1
  65. package/dist/{task-4HeGAS8o.d.mts → task--hlnpS7L.d.mts} +2 -2
  66. package/dist/{task-4HeGAS8o.d.mts.map → task--hlnpS7L.d.mts.map} +1 -1
  67. package/dist/task-CXF9VULl.cjs.map +1 -1
  68. package/dist/{task-DJpTteeJ.d.mts → task-DdTKZNtU.d.mts} +3 -1
  69. package/dist/task-DdTKZNtU.d.mts.map +1 -0
  70. package/dist/task-giCbpKzV.mjs.map +1 -1
  71. package/dist/{taskGraph-D0zFHF2p.d.mts → taskGraph-CB8ffMCz.d.mts} +2 -2
  72. package/dist/{taskGraph-D0zFHF2p.d.mts.map → taskGraph-CB8ffMCz.d.mts.map} +1 -1
  73. package/dist/{taskStore-C4vcUOzA.cjs → taskStore-B-BbY2Ci.cjs} +30 -36
  74. package/dist/taskStore-B-BbY2Ci.cjs.map +1 -0
  75. package/dist/{taskStore-BAi54FKL.mjs → taskStore-wuXXFCZT.mjs} +29 -35
  76. package/dist/taskStore-wuXXFCZT.mjs.map +1 -0
  77. package/dist/toolResponseEnvelope.d.mts +1 -1
  78. package/dist/toolSchema.d.mts +1 -1
  79. package/llms.txt +11 -0
  80. package/package.json +18 -17
  81. package/src/prompts/codemode-how-to-task/SKILL.md +40 -0
  82. package/src/types/webTasks.ts +1 -0
  83. package/dist/delegation-Dsqf7fUM.mjs.map +0 -1
  84. package/dist/delegation-frvEXhIz.cjs.map +0 -1
  85. package/dist/index-CA4Opp4r.d.mts.map +0 -1
  86. package/dist/index-qQGWsPum.d.mts.map +0 -1
  87. package/dist/logSinkTelemetry-BGb8WQBz.cjs.map +0 -1
  88. package/dist/logSinkTelemetry-BhbKdn-x.mjs.map +0 -1
  89. package/dist/paths-DajceJig.mjs.map +0 -1
  90. package/dist/paths-P-XvOUuH.cjs.map +0 -1
  91. package/dist/task-DJpTteeJ.d.mts.map +0 -1
  92. package/dist/taskStore-BAi54FKL.mjs.map +0 -1
  93. package/dist/taskStore-C4vcUOzA.cjs.map +0 -1
package/LICENSE CHANGED
@@ -1,21 +1,149 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Vuong Ngo
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ License text copyright © 2017 MariaDB Corporation Ab, All Rights Reserved.
2
+ "Business Source License" is a trademark of MariaDB Corporation Ab.
3
+
4
+ Parameters
5
+
6
+ Licensor: Agimon Pty Ltd
7
+ Licensed Work: Po, the software in the Po source repository and the
8
+ packages released from it, in each version released by
9
+ the Licensor.
10
+ The Licensed Work is (c) 2026 Agimon Pty Ltd.
11
+ Material identified as third-party in the "Third-party
12
+ components" section at the end of this file or in a
13
+ NOTICE file, and any package or directory whose own
14
+ license file grants a different license, is not part of
15
+ the Licensed Work and remains under its own license.
16
+ Additional Use Grant: You may make production use of the Licensed Work if
17
+ your use is Eligible Use. "Eligible Use" is production use that falls
18
+ within at least one of the following:
19
+
20
+ (a) Personal Use. Use by an individual for their own personal purposes,
21
+ and not on behalf of, or for the benefit of, an employer, client, or
22
+ other Organization. Use by an individual in the course of employment
23
+ or engagement by an Organization is use by that Organization.
24
+
25
+ (b) Small Organization Use. Use by or on behalf of an Organization whose
26
+ Annual Revenue is less than USD 1,000,000.
27
+
28
+ (c) Non-profit, Education and Research Use. Use, regardless of Annual
29
+ Revenue, by (i) an Organization registered or recognized as a
30
+ non-profit or charitable organization under the laws of its
31
+ jurisdiction, for its non-profit purposes; (ii) an accredited school,
32
+ college, or university, for teaching, learning, or academic research;
33
+ or (iii) a publicly funded research institution, for its research.
34
+
35
+ (d) Service Provider Use. Use by a consultant, contractor, agency, or other
36
+ service provider, regardless of its own Annual Revenue, solely to
37
+ build, deploy, host, operate, or support the Licensed Work for a client
38
+ whose own use would be Eligible Use under (a), (b), or (c). A service
39
+ provider's use for its own purposes is Eligible Use only if the service
40
+ provider itself qualifies under (b) or (c).
41
+
42
+
43
+ Hosted services. Offering the Licensed Work to third parties as a hosted
44
+ or managed service whose primary value is the Licensed Work is Eligible
45
+ Use only if each such third party's own use would be Eligible Use.
46
+
47
+ Definitions. "Organization" means any company, partnership, sole
48
+ proprietorship, trust, association, government body, or other entity, and
49
+ includes an individual acting in a business or professional capacity.
50
+ "Affiliate" means any entity that directly or indirectly controls, is
51
+ controlled by, or is under common control with an Organization, where
52
+ "control" means ownership of more than 50% of the voting interests of an
53
+ entity or the power to direct its management and policies by contract or
54
+ otherwise. "Annual Revenue" means the total gross revenue of an
55
+ Organization and all of its Affiliates combined, from all sources and
56
+ whether or not related to the Licensed Work, for its most recently
57
+ completed fiscal year, or, if it has not completed a fiscal year, for the
58
+ twelve months before the use (or since its formation, if shorter),
59
+ converted into US dollars at the average exchange rate for that period.
60
+ Proceeds of equity or debt financing are not revenue.
61
+
62
+ Threshold. If an Organization stops qualifying under (b), its existing
63
+ production use remains Eligible Use for 90 days after it stops
64
+ qualifying, after which it must obtain a commercial license or stop
65
+ production use. Use that was Eligible Use when it occurred never requires
66
+ a commercial license after the fact.
67
+ Change Date: Four years from the date a version of the Licensed Work
68
+ is first publicly released by the Licensor.
69
+ Change License: Apache License, Version 2.0
70
+
71
+ For information about alternative licensing arrangements for the Licensed
72
+ Work, please visit: https://agimon.ai/licensing
73
+
74
+ Notice
75
+
76
+ The Business Source License (this document, or the "License") is not an Open
77
+ Source license. However, the Licensed Work will eventually be made available
78
+ under an Open Source License, as stated in this License.
79
+
80
+ -----------------------------------------------------------------------------
81
+
82
+ Business Source License 1.1
83
+
84
+ Terms
85
+
86
+ The Licensor hereby grants you the right to copy, modify, create derivative
87
+ works, redistribute, and make non-production use of the Licensed Work. The
88
+ Licensor may make an Additional Use Grant, above, permitting limited
89
+ production use.
90
+
91
+ Effective on the Change Date, or the fourth anniversary of the first publicly
92
+ available distribution of a specific version of the Licensed Work under this
93
+ License, whichever comes first, the Licensor hereby grants you rights under
94
+ the terms of the Change License, and the rights granted in the paragraph
95
+ above terminate.
96
+
97
+ If your use of the Licensed Work does not comply with the requirements
98
+ currently in effect as described in this License, you must purchase a
99
+ commercial license from the Licensor, its affiliated entities, or authorized
100
+ resellers, or you must refrain from using the Licensed Work.
101
+
102
+ All copies of the original and modified Licensed Work, and derivative works
103
+ of the Licensed Work, are subject to this License. This License applies
104
+ separately for each version of the Licensed Work and the Change Date may vary
105
+ for each version of the Licensed Work released by Licensor.
106
+
107
+ You must conspicuously display this License on each original or modified copy
108
+ of the Licensed Work. If you receive the Licensed Work in original or
109
+ modified form from a third party, the terms and conditions set forth in this
110
+ License apply to your use of that work.
111
+
112
+ Any use of the Licensed Work in violation of this License will automatically
113
+ terminate your rights under this License for the current and all other
114
+ versions of the Licensed Work.
115
+
116
+ This License does not grant you any right in any trademark or logo of
117
+ Licensor or its affiliates (provided that you may use a trademark or logo of
118
+ Licensor as expressly required by this License).
119
+
120
+ TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON
121
+ AN “AS IS” BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS,
122
+ EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF
123
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND
124
+ TITLE.
125
+
126
+ MariaDB hereby grants you permission to use this License’s text to license
127
+ your works, and to refer to it using the trademark “Business Source License”,
128
+ as long as you comply with the Covenants of Licensor below.
129
+
130
+ Covenants of Licensor
131
+
132
+ In consideration of the right to use this License’s text and the “Business
133
+ Source License” name and trademark, Licensor covenants to MariaDB, and to all
134
+ other recipients of the licensed work to be provided by Licensor:
135
+
136
+ 1. To specify as the Change License the GPL Version 2.0 or any later version,
137
+ or a license that is compatible with GPL Version 2.0 or a later version,
138
+ where “compatible” means that software provided under the Change License can
139
+ be included in a program with software provided under GPL Version 2.0 or a
140
+ later version. Licensor may specify additional Change Licenses without
141
+ limitation.
142
+
143
+ 2. To either: (a) specify an additional grant of rights to use that does not
144
+ impose any additional restriction on the right granted in this License, as
145
+ the Additional Use Grant; or (b) insert the text “None”.
146
+
147
+ 3. To specify a Change Date.
148
+
149
+ 4. Not to modify this License in any other way.
package/README.md CHANGED
@@ -63,6 +63,16 @@ The reducer enforces lifecycle transitions and rejects dependency cycles. A grap
63
63
  non-deleted tasks by default; updates still apply when full, but new tasks are rejected until space
64
64
  is freed.
65
65
 
66
+ ## Tasks in code mode
67
+
68
+ When code mode is loaded, the `tasks` namespace covers every task action and the direct `task` tool is
69
+ withdrawn from the model for that session. `await tasks.snapshot()` returns a detached `TaskDocument`,
70
+ including deleted tasks, and never locks, writes, increments `rev`, or replaces the store cache. A
71
+ missing file returns an empty document; other read failures reject. `upsert`, `delete`, `clear`,
72
+ `assign` and `cancel` write through the same store and reducer as the tool and resolve to
73
+ `{ message, document }`; a refused change rejects. Without code mode, and on remote MCP, the `task`
74
+ tool stays available. The `codemode-how-to-task` skill carries the usage rules.
75
+
66
76
  ## Presentation
67
77
 
68
78
  The browser owns the task view and renderer. Terminal task shortcuts and overlays are retired; the native `task` tool remains available.
@@ -105,7 +115,7 @@ import { detectCycle, isBlocked, TaskStore } from '@agimon-ai/po-task';
105
115
  import type { Task, TaskStatus } from '@agimon-ai/po-task';
106
116
  ```
107
117
 
108
- Focused subpaths include `/toolSchema`, `/storeReducer`, `/storeTaskStore`, and `/delegationManager`. Native metadata selects server, browser, and explicit MCP facets; terminal facades are removed.
118
+ Focused subpaths include `/toolSchema`, `/storeReducer`, `/storeTaskStore`, and `/delegationManager`. Native metadata selects server and browser plugins and explicit MCP facets; terminal facades are removed.
109
119
 
110
120
  ## Source layout
111
121
 
@@ -126,6 +136,6 @@ Maintained by [Agimon](https://agimon.ai/about).
126
136
 
127
137
  ## License
128
138
 
129
- MIT
139
+ Business Source License 1.1: free for personal use, organisations under USD 1M revenue, non-profits and education. See [LICENSE](LICENSE) and https://agimon.ai/licensing.
130
140
 
131
141
  Native server routes live in `src/extensions`; browser routes own presentation. Services own persistence, delegation, and configuration, while models hold durable task documents and graphs. Public entries are flat, forwarding-only files in `src/exports`. Scope lifecycle cleanup belongs to the native server root, not a Pi factory. Terminal task overlays and their public facades are retired.
@@ -27,6 +27,7 @@ const TasksPayloadSchema = typebox.Type.Object({
27
27
  updatedAt: O(S),
28
28
  delegation: O(typebox.Type.Object({
29
29
  agent: O(S),
30
+ identity: O(S),
30
31
  state: O(S)
31
32
  }))
32
33
  })),
@@ -1 +1 @@
1
- {"version":3,"file":"apiContracts.cjs","names":["Type","defineApiContract"],"sources":["../src/schemas/apiContracts.ts"],"sourcesContent":["import { defineApiContract } from '@agimon-ai/po-core/apiContracts';\nimport { Type } from 'typebox';\n\nconst S = Type.String();\nconst N = Type.Number();\nconst O = Type.Optional;\nconst literals = <T extends string>(values: T[]) => Type.Union(values.map((value) => Type.Literal(value)));\nexport const TasksPayloadSchema = Type.Object({\n tasks: Type.Array(\n Type.Object({\n id: N,\n subject: S,\n description: O(S),\n activeForm: O(S),\n status: literals(['pending', 'in_progress', 'completed', 'failed', 'deleted']),\n blockedBy: Type.Array(N),\n owner: O(S),\n updatedAt: O(S),\n delegation: O(Type.Object({ agent: O(S), state: O(S) })),\n }),\n ),\n rev: N,\n});\nexport const apiContracts = defineApiContract({\n version: 1,\n http: [],\n dynamic: [],\n sockets: (['global', 'workspace'] as const).map((scope) => ({\n id: 'tasks.channel',\n scope,\n service: 'po.hub',\n member: 'task_graph',\n kind: 'channel',\n direction: 'server-to-client',\n description: 'Task graph channel payload.',\n input: TasksPayloadSchema,\n })),\n});\nexport default apiContracts;\n"],"mappings":";;;;;;;AAGA,MAAM,IAAIA,QAAAA,KAAK,OAAO;AACtB,MAAM,IAAIA,QAAAA,KAAK,OAAO;AACtB,MAAM,IAAIA,QAAAA,KAAK;AACf,MAAM,YAA8B,WAAgBA,QAAAA,KAAK,MAAM,OAAO,KAAK,UAAUA,QAAAA,KAAK,QAAQ,KAAK,CAAC,CAAC;AACzG,MAAa,qBAAqBA,QAAAA,KAAK,OAAO;CAC5C,OAAOA,QAAAA,KAAK,MACVA,QAAAA,KAAK,OAAO;EACV,IAAI;EACJ,SAAS;EACT,aAAa,EAAE,CAAC;EAChB,YAAY,EAAE,CAAC;EACf,QAAQ,SAAS;GAAC;GAAW;GAAe;GAAa;GAAU;EAAS,CAAC;EAC7E,WAAWA,QAAAA,KAAK,MAAM,CAAC;EACvB,OAAO,EAAE,CAAC;EACV,WAAW,EAAE,CAAC;EACd,YAAY,EAAEA,QAAAA,KAAK,OAAO;GAAE,OAAO,EAAE,CAAC;GAAG,OAAO,EAAE,CAAC;EAAE,CAAC,CAAC;CACzD,CAAC,CACH;CACA,KAAK;AACP,CAAC;AACD,MAAa,gBAAA,GAAeC,gCAAAA,kBAAAA,CAAkB;CAC5C,SAAS;CACT,MAAM,CAAC;CACP,SAAS,CAAC;CACV,SAAU,CAAC,UAAU,WAAW,CAAC,CAAW,KAAK,WAAW;EAC1D,IAAI;EACJ;EACA,SAAS;EACT,QAAQ;EACR,MAAM;EACN,WAAW;EACX,aAAa;EACb,OAAO;CACT,EAAE;AACJ,CAAC"}
1
+ {"version":3,"file":"apiContracts.cjs","names":["Type","defineApiContract"],"sources":["../src/schemas/apiContracts.ts"],"sourcesContent":["import { defineApiContract } from '@agimon-ai/po-core/apiContracts';\nimport { Type } from 'typebox';\n\nconst S = Type.String();\nconst N = Type.Number();\nconst O = Type.Optional;\nconst literals = <T extends string>(values: T[]) => Type.Union(values.map((value) => Type.Literal(value)));\nexport const TasksPayloadSchema = Type.Object({\n tasks: Type.Array(\n Type.Object({\n id: N,\n subject: S,\n description: O(S),\n activeForm: O(S),\n status: literals(['pending', 'in_progress', 'completed', 'failed', 'deleted']),\n blockedBy: Type.Array(N),\n owner: O(S),\n updatedAt: O(S),\n delegation: O(Type.Object({ agent: O(S), identity: O(S), state: O(S) })),\n }),\n ),\n rev: N,\n});\nexport const apiContracts = defineApiContract({\n version: 1,\n http: [],\n dynamic: [],\n sockets: (['global', 'workspace'] as const).map((scope) => ({\n id: 'tasks.channel',\n scope,\n service: 'po.hub',\n member: 'task_graph',\n kind: 'channel',\n direction: 'server-to-client',\n description: 'Task graph channel payload.',\n input: TasksPayloadSchema,\n })),\n});\nexport default apiContracts;\n"],"mappings":";;;;;;;AAGA,MAAM,IAAIA,QAAAA,KAAK,OAAO;AACtB,MAAM,IAAIA,QAAAA,KAAK,OAAO;AACtB,MAAM,IAAIA,QAAAA,KAAK;AACf,MAAM,YAA8B,WAAgBA,QAAAA,KAAK,MAAM,OAAO,KAAK,UAAUA,QAAAA,KAAK,QAAQ,KAAK,CAAC,CAAC;AACzG,MAAa,qBAAqBA,QAAAA,KAAK,OAAO;CAC5C,OAAOA,QAAAA,KAAK,MACVA,QAAAA,KAAK,OAAO;EACV,IAAI;EACJ,SAAS;EACT,aAAa,EAAE,CAAC;EAChB,YAAY,EAAE,CAAC;EACf,QAAQ,SAAS;GAAC;GAAW;GAAe;GAAa;GAAU;EAAS,CAAC;EAC7E,WAAWA,QAAAA,KAAK,MAAM,CAAC;EACvB,OAAO,EAAE,CAAC;EACV,WAAW,EAAE,CAAC;EACd,YAAY,EAAEA,QAAAA,KAAK,OAAO;GAAE,OAAO,EAAE,CAAC;GAAG,UAAU,EAAE,CAAC;GAAG,OAAO,EAAE,CAAC;EAAE,CAAC,CAAC;CACzE,CAAC,CACH;CACA,KAAK;AACP,CAAC;AACD,MAAa,gBAAA,GAAeC,gCAAAA,kBAAAA,CAAkB;CAC5C,SAAS;CACT,MAAM,CAAC;CACP,SAAS,CAAC;CACV,SAAU,CAAC,UAAU,WAAW,CAAC,CAAW,KAAK,WAAW;EAC1D,IAAI;EACJ;EACA,SAAS;EACT,QAAQ;EACR,MAAM;EACN,WAAW;EACX,aAAa;EACb,OAAO;CACT,EAAE;AACJ,CAAC"}
@@ -23,6 +23,7 @@ const TasksPayloadSchema = Type.Object({
23
23
  updatedAt: O(S),
24
24
  delegation: O(Type.Object({
25
25
  agent: O(S),
26
+ identity: O(S),
26
27
  state: O(S)
27
28
  }))
28
29
  })),
@@ -1 +1 @@
1
- {"version":3,"file":"apiContracts.mjs","names":[],"sources":["../src/schemas/apiContracts.ts"],"sourcesContent":["import { defineApiContract } from '@agimon-ai/po-core/apiContracts';\nimport { Type } from 'typebox';\n\nconst S = Type.String();\nconst N = Type.Number();\nconst O = Type.Optional;\nconst literals = <T extends string>(values: T[]) => Type.Union(values.map((value) => Type.Literal(value)));\nexport const TasksPayloadSchema = Type.Object({\n tasks: Type.Array(\n Type.Object({\n id: N,\n subject: S,\n description: O(S),\n activeForm: O(S),\n status: literals(['pending', 'in_progress', 'completed', 'failed', 'deleted']),\n blockedBy: Type.Array(N),\n owner: O(S),\n updatedAt: O(S),\n delegation: O(Type.Object({ agent: O(S), state: O(S) })),\n }),\n ),\n rev: N,\n});\nexport const apiContracts = defineApiContract({\n version: 1,\n http: [],\n dynamic: [],\n sockets: (['global', 'workspace'] as const).map((scope) => ({\n id: 'tasks.channel',\n scope,\n service: 'po.hub',\n member: 'task_graph',\n kind: 'channel',\n direction: 'server-to-client',\n description: 'Task graph channel payload.',\n input: TasksPayloadSchema,\n })),\n});\nexport default apiContracts;\n"],"mappings":";;;AAGA,MAAM,IAAI,KAAK,OAAO;AACtB,MAAM,IAAI,KAAK,OAAO;AACtB,MAAM,IAAI,KAAK;AACf,MAAM,YAA8B,WAAgB,KAAK,MAAM,OAAO,KAAK,UAAU,KAAK,QAAQ,KAAK,CAAC,CAAC;AACzG,MAAa,qBAAqB,KAAK,OAAO;CAC5C,OAAO,KAAK,MACV,KAAK,OAAO;EACV,IAAI;EACJ,SAAS;EACT,aAAa,EAAE,CAAC;EAChB,YAAY,EAAE,CAAC;EACf,QAAQ,SAAS;GAAC;GAAW;GAAe;GAAa;GAAU;EAAS,CAAC;EAC7E,WAAW,KAAK,MAAM,CAAC;EACvB,OAAO,EAAE,CAAC;EACV,WAAW,EAAE,CAAC;EACd,YAAY,EAAE,KAAK,OAAO;GAAE,OAAO,EAAE,CAAC;GAAG,OAAO,EAAE,CAAC;EAAE,CAAC,CAAC;CACzD,CAAC,CACH;CACA,KAAK;AACP,CAAC;AACD,MAAa,eAAe,kBAAkB;CAC5C,SAAS;CACT,MAAM,CAAC;CACP,SAAS,CAAC;CACV,SAAU,CAAC,UAAU,WAAW,CAAC,CAAW,KAAK,WAAW;EAC1D,IAAI;EACJ;EACA,SAAS;EACT,QAAQ;EACR,MAAM;EACN,WAAW;EACX,aAAa;EACb,OAAO;CACT,EAAE;AACJ,CAAC"}
1
+ {"version":3,"file":"apiContracts.mjs","names":[],"sources":["../src/schemas/apiContracts.ts"],"sourcesContent":["import { defineApiContract } from '@agimon-ai/po-core/apiContracts';\nimport { Type } from 'typebox';\n\nconst S = Type.String();\nconst N = Type.Number();\nconst O = Type.Optional;\nconst literals = <T extends string>(values: T[]) => Type.Union(values.map((value) => Type.Literal(value)));\nexport const TasksPayloadSchema = Type.Object({\n tasks: Type.Array(\n Type.Object({\n id: N,\n subject: S,\n description: O(S),\n activeForm: O(S),\n status: literals(['pending', 'in_progress', 'completed', 'failed', 'deleted']),\n blockedBy: Type.Array(N),\n owner: O(S),\n updatedAt: O(S),\n delegation: O(Type.Object({ agent: O(S), identity: O(S), state: O(S) })),\n }),\n ),\n rev: N,\n});\nexport const apiContracts = defineApiContract({\n version: 1,\n http: [],\n dynamic: [],\n sockets: (['global', 'workspace'] as const).map((scope) => ({\n id: 'tasks.channel',\n scope,\n service: 'po.hub',\n member: 'task_graph',\n kind: 'channel',\n direction: 'server-to-client',\n description: 'Task graph channel payload.',\n input: TasksPayloadSchema,\n })),\n});\nexport default apiContracts;\n"],"mappings":";;;AAGA,MAAM,IAAI,KAAK,OAAO;AACtB,MAAM,IAAI,KAAK,OAAO;AACtB,MAAM,IAAI,KAAK;AACf,MAAM,YAA8B,WAAgB,KAAK,MAAM,OAAO,KAAK,UAAU,KAAK,QAAQ,KAAK,CAAC,CAAC;AACzG,MAAa,qBAAqB,KAAK,OAAO;CAC5C,OAAO,KAAK,MACV,KAAK,OAAO;EACV,IAAI;EACJ,SAAS;EACT,aAAa,EAAE,CAAC;EAChB,YAAY,EAAE,CAAC;EACf,QAAQ,SAAS;GAAC;GAAW;GAAe;GAAa;GAAU;EAAS,CAAC;EAC7E,WAAW,KAAK,MAAM,CAAC;EACvB,OAAO,EAAE,CAAC;EACV,WAAW,EAAE,CAAC;EACd,YAAY,EAAE,KAAK,OAAO;GAAE,OAAO,EAAE,CAAC;GAAG,UAAU,EAAE,CAAC;GAAG,OAAO,EAAE,CAAC;EAAE,CAAC,CAAC;CACzE,CAAC,CACH;CACA,KAAK;AACP,CAAC;AACD,MAAa,eAAe,kBAAkB;CAC5C,SAAS;CACT,MAAM,CAAC;CACP,SAAS,CAAC;CACV,SAAU,CAAC,UAAU,WAAW,CAAC,CAAW,KAAK,WAAW;EAC1D,IAAI;EACJ;EACA,SAAS;EACT,QAAQ;EACR,MAAM;EACN,WAAW;EACX,aAAa;EACb,OAAO;CACT,EAAE;AACJ,CAAC"}
@@ -340,7 +340,7 @@ var DelegationManager = class DelegationManager {
340
340
  };
341
341
  }
342
342
  async cancel(taskId) {
343
- const task = this.options.store.read().tasks.find((candidate) => candidate.id === taskId);
343
+ const task = (await this.options.store.readAsync()).tasks.find((candidate) => candidate.id === taskId);
344
344
  if (!task) return {
345
345
  ok: false,
346
346
  message: `#${taskId} not found`
@@ -457,7 +457,8 @@ var DelegationManager = class DelegationManager {
457
457
  ...delegation,
458
458
  state: "running",
459
459
  startedAt: delegation.startedAt ?? this.now(),
460
- ...runId ? { runId } : {}
460
+ ...runId ? { runId } : {},
461
+ ...event.identity ? { identity: event.identity } : {}
461
462
  }
462
463
  }))).then(() => this.options.onChange?.()).catch((error) => {
463
464
  this.report(TASK_EVENT.delegationStartFailed, error, {
@@ -623,4 +624,4 @@ var DelegationManager = class DelegationManager {
623
624
  //#endregion
624
625
  export { ERR_NO_RUNTIME as a, ERR_CHILD_SESSION as i, DelegationManager as n, NOTIFY_CUSTOM_TYPE as o, ERR_CANCEL_UNACKNOWLEDGED as r, BACKGROUND_WORK_PROVIDER as t };
625
626
 
626
- //# sourceMappingURL=delegation-Dsqf7fUM.mjs.map
627
+ //# sourceMappingURL=delegation-5TOl_dEq.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"delegation-5TOl_dEq.mjs","names":[],"sources":["../src/services/delegation/index.ts"],"sourcesContent":["import {\n type DelegationAccepted as DelegationAcceptedPayload,\n PO_DELEGATION_ACCEPTED_EVENT,\n PO_DELEGATION_FINISHED_EVENT,\n PO_DELEGATION_STARTED_EVENT,\n PO_DELEGATION_UPDATED_EVENT,\n type PoDelegationService,\n type DelegationResult,\n type DelegationStarted as DelegationStartedPayload,\n type DelegationUpdate,\n type InlineAgent,\n} from '@agimon-ai/po-core/delegation';\nimport type { Context } from '@deepseek-ai/cordis';\n\nimport { isBlocked, isTaskListComplete } from '../../models/taskGraph';\nimport { MAX_BRIEF_FILES } from '../../types/delegation';\nimport { TASK_EVENT, type TaskEventName, type TaskFailureReporter } from '../../types/telemetry';\nimport { reconcileOrphanedDelegations } from '../reconcile';\nimport type { TaskStore } from '../taskStore';\n\nexport { MAX_BRIEF_FILES };\nimport { isDelegationActive, type Task, type TaskDelegation, type TaskDocument } from '../../models/task';\n\nexport const NOTIFY_CUSTOM_TYPE = 'po-task-notify';\nexport const BACKGROUND_WORK_PROVIDER = 'po-task';\n\nconst DEFAULT_STARTED_TIMEOUT_MS = 5000;\nconst DEFAULT_RUN_TIMEOUT_MS = 20 * 60 * 1000;\nconst DEFAULT_CANCEL_TIMEOUT_MS = 10_000;\nconst MAX_RUN_TIMEOUT_GRACE_MS = 60_000;\nconst MAX_STORED_OUTPUT = 4000;\n/**\n * Cap on files rendered into a brief. Exported so the tool schema can state the\n * same number to the model rather than restating it and drifting.\n */\nconst MAX_BRIEF_NOTES = 1500;\nconst COMPLETED_STATE = 'completed';\nconst FAILED_STATE = 'failed';\nconst CANCELLED_STATE = 'cancelled';\nconst TIMED_OUT_STATUS = 'timed_out';\nconst DELETED_STATUS: Task['status'] = 'deleted';\n\nconst TASK_ID_ATTRIBUTE = 'task.id';\nconst REQUEST_ID_ATTRIBUTE = 'delegation.request_id';\n// `_name` suffix is load-bearing: the telemetry redactor drops string values\n// whose key has no safe meaning, and a bare `delegation.agent` is dropped.\nconst AGENT_ATTRIBUTE = 'delegation.agent_name';\nconst PID_ATTRIBUTE = 'delegation.pid';\nconst CONTEXT_PRESENT_ATTRIBUTE = 'delegation.context_present';\nconst CONTEXT_FILE_COUNT_ATTRIBUTE = 'delegation.context_file_count';\nconst CONTEXT_NOTES_LENGTH_ATTRIBUTE = 'delegation.context_notes_length';\nconst BRIEF_LENGTH_ATTRIBUTE = 'delegation.brief_length';\nconst TOOL_COUNT_ATTRIBUTE = 'delegation.tool_count';\nconst DURATION_MS_ATTRIBUTE = 'delegation.duration_ms';\nconst OUTCOME_ATTRIBUTE = 'delegation.outcome';\n\ntype SettlementState = typeof COMPLETED_STATE | typeof FAILED_STATE | typeof CANCELLED_STATE;\n\nexport const ERR_NO_RUNTIME =\n 'No subagent runtime responded. Delegation needs the subagents extension — relaunch po with agents enabled.';\nexport const ERR_CHILD_SESSION =\n 'assign is only available in the main session. Update this task directly instead of re-delegating it.';\nexport const ERR_CANCEL_UNACKNOWLEDGED = 'Subagent did not acknowledge the cancel request';\n\n/** Live progress from a running subagent. Kept in memory: persisting per-tool\n * ticks would rewrite the store file every second for no durable benefit. */\nexport interface DelegationProgress {\n agent: string;\n currentTool?: string;\n toolCount?: number;\n tokens?: number;\n /** Latest child-runtime duration baseline, excluding assignment wait. */\n durationMs?: number;\n /** Wall-clock time at which durationMs was observed or rebased. */\n durationObservedAt?: number;\n /** Assign-time context-pack shape, carried so the completion event can be\n * grouped by it without joining back to the assignment event. */\n contextFileCount?: number;\n contextNotesLength?: number;\n}\n\nexport type DelegationNotifier = (\n message: { customType: string; content: string; display: boolean },\n options?: { triggerTurn?: boolean; deliverAs?: 'steer' | 'followUp' | 'nextTurn' },\n) => void;\n\nexport interface DelegationPlatform {\n readonly environment: Readonly<Record<string, string | undefined>>;\n readonly processId: number;\n readonly createRequestId: () => string;\n readonly formatBriefPath: (entry: string, cwd: string) => string;\n}\n\nexport interface DelegationManagerOptions {\n store: TaskStore;\n cwd: string;\n platform: DelegationPlatform;\n notify?: DelegationNotifier;\n getSessionId?: () => string | undefined;\n onChange?: () => void;\n startedTimeoutMs?: number;\n /** How long a started run may go without reporting a result. */\n runTimeoutMs?: number;\n /** How long to wait for a cancelled run to report back before forcing it. */\n cancelTimeoutMs?: number;\n now?: () => string;\n nowMs?: () => number;\n /** Called when a completion notification could not be delivered. */\n onNotifyError: (error: unknown, taskId: number) => void;\n /** Where other swallowed delegation failures go. */\n report?: TaskFailureReporter;\n}\n\nexport interface AssignOptions {\n agent?: string;\n inlineAgent?: InlineAgent;\n instructions?: string;\n /** Paths the parent already located, rendered into the brief so the child\n * skips rediscovering them. */\n relevantFiles?: string[];\n /** Facts the parent already established, rendered into the brief so the child\n * does not re-derive them. */\n priorFindings?: string;\n model?: string;\n context?: 'fresh' | 'fork';\n signal?: AbortSignal;\n}\n\nexport interface DelegationOutcome {\n ok: boolean;\n message: string;\n}\n\n/** Result of the guarded store mutation that claims a task for delegation. */\ninterface AssignAttempt extends DelegationOutcome {\n task?: Task;\n}\n\ninterface PendingTask {\n readonly taskId: number;\n readonly sessionId?: string;\n}\n\nfunction truncate(value: string | undefined, limit = MAX_STORED_OUTPUT): string | undefined {\n if (!value) return undefined;\n return value.length <= limit ? value : `${value.slice(0, limit)}\\n… (truncated)`;\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/** The assign-time context pack, normalized once for the brief and the telemetry. */\ninterface BriefContext {\n files: string[];\n notes?: string;\n}\n\n/** Normalize the parent context with host-owned path semantics. */\nfunction briefContext(options: AssignOptions, cwd: string, platform: DelegationPlatform): BriefContext {\n const files = new Set<string>();\n for (const entry of options.relevantFiles ?? []) {\n if (files.size >= MAX_BRIEF_FILES) break;\n const normalized = platform.formatBriefPath(entry.trim(), cwd);\n if (normalized && normalized !== '.') files.add(normalized);\n }\n return { files: [...files], notes: truncate(options.priorFindings?.trim(), MAX_BRIEF_NOTES) };\n}\n\n/**\n * Build the brief handed to the subagent.\n *\n * Po Team owns the child tool surface and the parent owns the task record.\n * Keeping those responsibilities explicit prevents a child from attempting to\n * call a task tool that is not loaded in its runtime, while still giving it a\n * reliable path to ask the parent for a decision.\n *\n * The context pack is the parent's verified discovery handed over. The whole\n * block is omitted when nothing was supplied: this brief is the child's whole\n * starting context, so an empty section header is pure token cost.\n */\nfunction buildBrief(task: Task, instructions: string | undefined, context: BriefContext): string {\n const sections = [`Task #${task.id}: ${task.subject}`];\n if (task.description) sections.push(task.description);\n if (instructions) sections.push(instructions);\n if (context.files.length > 0 || context.notes) {\n const contextLines = ['Parent context — consume before repository discovery:'];\n if (context.files.length > 0) {\n contextLines.push(`- Parent-verified files (read these first with direct reads): ${context.files.join(', ')}`);\n }\n if (context.notes) {\n contextLines.push(\n `- Established facts (do not re-derive unless direct evidence contradicts them): ${context.notes}`,\n );\n }\n contextLines.push(\n 'This pack satisfies initial repository/context exploration. Do not begin with repository-wide listing, find, or grep. Expand only after consuming the pack and naming a concrete missing dependency or invalid path; search narrowly for that item and state why.',\n );\n sections.push(contextLines.join('\\n'));\n }\n sections.push(\n 'Coordination: work directly without changing the task record; ask main through intercom only for blockers or decisions; report changed files and verification when done.',\n );\n return sections.join('\\n\\n');\n}\n\n/**\n * Owns the lifecycle of tasks delegated to subagents.\n *\n * Delegation rides Team's injected Cordis service rather than spawning\n * processes directly, so po-task stays decoupled from the subagent runtime\n * and degrades to a clear error when that service is not loaded.\n *\n * Liveness rule: every entry in `pendingTasks` has a timer armed against it, so\n * a delegation always has a deadline no matter which phase it is in. Losing\n * that pairing is what previously left tasks running forever.\n */\nexport class DelegationManager {\n private readonly options: DelegationManagerOptions;\n private readonly progress = new Map<string, DelegationProgress>();\n private readonly pendingTasks = new Map<string, PendingTask>();\n private readonly settlingRequests = new Set<string>();\n private readonly timers = new Map<string, ReturnType<typeof setTimeout>>();\n private readonly subscriptions: Array<() => void> = [];\n private service: PoDelegationService | undefined;\n\n constructor(options: DelegationManagerOptions) {\n this.options = options;\n }\n\n setCwd(cwd: string): void {\n this.options.cwd = cwd;\n }\n\n private now(): string {\n return this.options.now?.() ?? new Date().toISOString();\n }\n\n private nowMs(): number {\n return this.options.nowMs?.() ?? Date.now();\n }\n\n private get runTimeoutMs(): number {\n return this.options.runTimeoutMs ?? DEFAULT_RUN_TIMEOUT_MS;\n }\n\n private report(event: TaskEventName, error: unknown, attributes?: Record<string, string | number | boolean>): void {\n this.options.report?.error(event, error, attributes);\n }\n\n /** True in a session that is itself a subagent child. */\n get isChildSession(): boolean {\n return Boolean(this.options.platform.environment.PI_SUBAGENT_CHILD);\n }\n\n /** Live progress for a task, for the overlay to render. */\n progressFor(task: Task): DelegationProgress | undefined {\n const requestId = task.delegation?.requestId;\n return requestId ? this.progress.get(requestId) : undefined;\n }\n\n /** Displayed runtime duration, rebased from the latest child observation. */\n static elapsedMs(progress: DelegationProgress, nowMs = Date.now()): number {\n const baseline = progress.durationMs ?? 0;\n const observedAt = progress.durationObservedAt ?? nowMs;\n return baseline + Math.max(0, nowMs - observedAt);\n }\n\n /** Rebind to the active Team service without stacking lifecycle listeners. */\n bind(ctx: Context, service: PoDelegationService): () => void {\n this.unbind();\n this.service = service;\n this.subscriptions.push(\n ctx.on(PO_DELEGATION_ACCEPTED_EVENT, (event) => {\n this.handleAccepted(event);\n }),\n ctx.on(PO_DELEGATION_STARTED_EVENT, (event) => {\n this.handleStarted(event);\n }),\n ctx.on(PO_DELEGATION_UPDATED_EVENT, (event) => {\n this.handleUpdate(event);\n }),\n ctx.on(PO_DELEGATION_FINISHED_EVENT, (event) => {\n void this.handleResponse(event).catch((error: unknown) => {\n this.report(TASK_EVENT.delegationResponseFailed, error, { [REQUEST_ID_ATTRIBUTE]: event.requestId });\n });\n }),\n );\n return () => {\n if (this.service === service) this.unbind();\n };\n }\n\n /** Remove only the cross-package binding; task state and watchdogs remain live. */\n unbind(): void {\n for (const unsubscribe of this.subscriptions.splice(0)) unsubscribe();\n this.service = undefined;\n }\n\n /** Items still in flight, surfaced so auto-stop will not kill the harness. */\n listActiveWork(): Array<{ id: string; sessionId: string }> {\n return [...this.pendingTasks.entries()].flatMap(([requestId, pending]) =>\n pending.sessionId ? [{ id: `task-${pending.taskId}:${requestId}`, sessionId: pending.sessionId }] : [],\n );\n }\n\n /**\n * Return tasks nothing can finish to `pending`.\n *\n * The live request set is read inside the mutation so a delegation assigned\n * while the lock was contended is not mistaken for a leftover.\n */\n async reconcile(isCurrent: () => boolean = () => true): Promise<Task[]> {\n const { value } = await this.options.store.mutate((document) => {\n if (!isCurrent()) return { value: [] as Task[] };\n const result = reconcileOrphanedDelegations(document, this.now(), undefined, {\n pid: this.options.platform.processId,\n liveRequestIds: new Set(this.pendingTasks.keys()),\n });\n if (result.orphaned.length === 0) return { value: [] as Task[] };\n return { document: result.document, value: result.orphaned };\n });\n\n if (!isCurrent()) return [];\n for (const task of value) {\n this.options.report?.warn(TASK_EVENT.delegationOrphaned, new Error(task.delegation?.result?.error ?? ''), {\n [TASK_ID_ATTRIBUTE]: task.id,\n ...(task.delegation?.agent ? { [AGENT_ATTRIBUTE]: task.delegation.agent } : {}),\n ...(task.delegation?.pid === undefined ? {} : { [PID_ATTRIBUTE]: task.delegation.pid }),\n });\n }\n\n if (value.length > 0) this.options.onChange?.();\n return value;\n }\n\n async assign(taskId: number, options: AssignOptions): Promise<DelegationOutcome> {\n const agent = options.agent?.trim();\n if (!agent) return { ok: false, message: 'agent required for assign' };\n if (this.isChildSession) return { ok: false, message: ERR_CHILD_SESSION };\n if (options.signal?.aborted) return { ok: false, message: 'delegation cancelled before it started' };\n\n const requestId = this.options.platform.createRequestId();\n const startedAt = this.now();\n const sessionId = this.options.getSessionId?.();\n const context = briefContext(options, this.options.cwd, this.options.platform);\n\n const { value: outcome } = await this.options.store.mutate<AssignAttempt>((current) => {\n const index = current.tasks.findIndex((task) => task.id === taskId);\n if (index === -1) return { value: { ok: false, message: `#${taskId} not found` } };\n\n const task = current.tasks[index];\n if (task.status === DELETED_STATUS) return { value: { ok: false, message: `#${taskId} is deleted` } };\n if (task.status === COMPLETED_STATE) {\n return { value: { ok: false, message: `#${taskId} is already completed` } };\n }\n if (isDelegationActive(task)) {\n return { value: { ok: false, message: `#${taskId} is already delegated to ${task.delegation?.agent}` } };\n }\n if (isBlocked(current.tasks, task)) {\n const blockers = (task.blockedBy ?? []).map((id) => `#${id}`).join(', ');\n return { value: { ok: false, message: `#${taskId} is blocked by ${blockers}` } };\n }\n\n const delegation: TaskDelegation = {\n requestId,\n agent,\n state: 'requested',\n pid: this.options.platform.processId,\n startedAt,\n ...(sessionId ? { sessionId } : {}),\n ...(options.model ? { model: options.model } : {}),\n };\n\n const tasks = [...current.tasks];\n tasks[index] = { ...task, owner: agent, updatedAt: startedAt, delegation };\n return {\n document: { ...current, tasks },\n value: { ok: true, message: '', task: tasks[index] },\n };\n });\n\n if (!outcome.ok || !outcome.task) return { ok: false, message: outcome.message };\n\n const contextNotesLength = context.notes?.length ?? 0;\n this.pendingTasks.set(requestId, { taskId, sessionId });\n this.progress.set(requestId, { agent, contextFileCount: context.files.length, contextNotesLength });\n this.armStartedTimeout(requestId);\n this.options.onChange?.();\n const request = {\n requestId,\n taskId,\n agent,\n ...(options.inlineAgent ? { inlineAgent: options.inlineAgent } : {}),\n prompt: buildBrief(outcome.task, options.instructions, context),\n ...(options.context ? { context: options.context } : {}),\n cwd: this.options.cwd,\n artifacts: true,\n timeoutMs: this.runTimeoutMs,\n runMode: 'detached' as const,\n teamTask: { id: String(outcome.task.id), subject: outcome.task.subject },\n ...(options.model ? { model: options.model } : {}),\n };\n\n try {\n const service = this.service;\n if (!service) throw new Error(ERR_NO_RUNTIME);\n void service.request(request).catch((error: unknown) => {\n this.report(TASK_EVENT.delegationRequestFailed, error, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n [AGENT_ATTRIBUTE]: agent,\n });\n this.settleDetached(requestId, FAILED_STATE, {\n status: FAILED_STATE,\n error: `Delegation request failed: ${messageOf(error)}`,\n });\n });\n } catch (error) {\n this.report(TASK_EVENT.delegationRequestFailed, error, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n [AGENT_ATTRIBUTE]: agent,\n });\n const detail = messageOf(error);\n await this.settle(requestId, FAILED_STATE, {\n status: FAILED_STATE,\n error: `Delegation request failed: ${detail}`,\n });\n return { ok: false, message: `Could not dispatch #${taskId} to ${agent}: ${detail}` };\n }\n\n // Recorded only after the service accepted the request call, so it means a\n // brief actually entered Team's state machine rather than merely being assembled.\n this.options.report?.event(TASK_EVENT.delegationAssigned, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n [AGENT_ATTRIBUTE]: agent,\n [CONTEXT_PRESENT_ATTRIBUTE]: context.files.length > 0 || contextNotesLength > 0,\n [CONTEXT_FILE_COUNT_ATTRIBUTE]: context.files.length,\n [CONTEXT_NOTES_LENGTH_ATTRIBUTE]: contextNotesLength,\n [BRIEF_LENGTH_ATTRIBUTE]: request.prompt.length,\n });\n\n return {\n ok: true,\n message: `Delegated #${taskId} to ${agent} in the background. It runs independently of this turn and will notify you when it finishes. Continue non-overlapping work, or end your turn.`,\n };\n }\n\n async cancel(taskId: number): Promise<DelegationOutcome> {\n const document = await this.options.store.readAsync();\n const task = document.tasks.find((candidate) => candidate.id === taskId);\n if (!task) return { ok: false, message: `#${taskId} not found` };\n if (!task.delegation || !isDelegationActive(task)) {\n return { ok: false, message: `#${taskId} has no running delegation` };\n }\n\n const { requestId } = task.delegation;\n this.service?.cancel({ requestId });\n // Only this session can force the outcome; a delegation owned elsewhere\n // gets the request and nothing more.\n this.armCancelTimeout(requestId);\n return { ok: true, message: `Cancelling delegation for #${taskId} (${task.delegation.agent})` };\n }\n\n /** Settle without awaiting, reporting rather than dropping a failure. */\n private settleDetached(\n requestId: string,\n state: SettlementState,\n result: TaskDelegation['result'],\n event: TaskEventName = TASK_EVENT.delegationSettleFailed,\n ): void {\n void this.settle(requestId, state, result).catch((error: unknown) => {\n this.report(event, error, { [REQUEST_ID_ATTRIBUTE]: requestId });\n });\n }\n\n /**\n * Fail a delegation that nobody acknowledged.\n *\n * Provider loss or a stalled Team runtime can still leave a dispatched\n * request silent. Without this acknowledgement deadline the task would sit\n * in `requested` forever.\n */\n private armStartedTimeout(requestId: string): void {\n this.armTimer(requestId, this.options.startedTimeoutMs ?? DEFAULT_STARTED_TIMEOUT_MS, () => {\n this.settleDetached(requestId, FAILED_STATE, { status: FAILED_STATE, error: ERR_NO_RUNTIME });\n });\n }\n\n /**\n * Bound a run that already started.\n *\n * The request carries the same budget, so in the normal case the runtime ends\n * the run itself and reports a richer result. The grace period biases toward\n * that answer; this timer only covers a runtime that goes silent, which is\n * precisely the case where no response event will ever arrive.\n */\n private armRunTimeout(requestId: string): void {\n const grace = Math.min(MAX_RUN_TIMEOUT_GRACE_MS, this.runTimeoutMs);\n this.armTimer(requestId, this.runTimeoutMs + grace, () => {\n const taskId = this.pendingTasks.get(requestId)?.taskId;\n const agent = this.progress.get(requestId)?.agent;\n const error = new Error(`Delegation produced no result within ${this.runTimeoutMs}ms`);\n this.options.report?.warn(TASK_EVENT.delegationTimedOut, error, {\n ...(taskId === undefined ? {} : { [TASK_ID_ATTRIBUTE]: taskId }),\n [REQUEST_ID_ATTRIBUTE]: requestId,\n ...(agent ? { [AGENT_ATTRIBUTE]: agent } : {}),\n });\n this.service?.cancel({ requestId, reason: error.message });\n this.settleDetached(requestId, FAILED_STATE, { status: TIMED_OUT_STATUS, error: error.message });\n });\n }\n\n /**\n * Guarantee a cancel reaches a terminal state.\n *\n * Calling the service is a request, not an outcome: a runtime that has\n * already forgotten the request answers nothing at all. The window still\n * favours a real response, which carries the run's partial output.\n */\n private armCancelTimeout(requestId: string): void {\n if (!this.pendingTasks.has(requestId)) return;\n this.armTimer(requestId, this.options.cancelTimeoutMs ?? DEFAULT_CANCEL_TIMEOUT_MS, () => {\n this.settleDetached(requestId, CANCELLED_STATE, {\n status: CANCELLED_STATE,\n error: ERR_CANCEL_UNACKNOWLEDGED,\n });\n });\n }\n\n private armTimer(requestId: string, delayMs: number, onFire: () => void): void {\n this.clearTimer(requestId);\n const timer = setTimeout(onFire, delayMs);\n timer.unref?.();\n this.timers.set(requestId, timer);\n }\n\n private clearTimer(requestId: string): void {\n const timer = this.timers.get(requestId);\n if (timer) clearTimeout(timer);\n this.timers.delete(requestId);\n }\n\n /** Runtime acknowledgement moves the request off the short extension-presence watchdog while launch is in flight. */\n private handleAccepted(event: DelegationAcceptedPayload): void {\n if (!this.pendingTasks.has(event.requestId)) return;\n this.armRunTimeout(event.requestId);\n }\n\n private handleStarted(event: DelegationStartedPayload): void {\n const { runId } = event;\n const taskId = this.pendingTasks.get(event.requestId)?.taskId;\n if (taskId === undefined) return;\n this.armRunTimeout(event.requestId);\n const existing = this.progress.get(event.requestId);\n if (existing) {\n this.progress.set(event.requestId, {\n ...existing,\n durationMs: existing.durationMs ?? 0,\n durationObservedAt: existing.durationObservedAt ?? this.nowMs(),\n });\n }\n\n void this.options.store\n .mutate((document) =>\n this.patchDelegation(document, event.requestId, (task, delegation) => ({\n ...task,\n status: task.status === COMPLETED_STATE ? task.status : 'in_progress',\n delegation: {\n ...delegation,\n state: 'running',\n startedAt: delegation.startedAt ?? this.now(),\n ...(runId ? { runId } : {}),\n ...(event.identity ? { identity: event.identity } : {}),\n },\n })),\n )\n .then(() => this.options.onChange?.())\n .catch((error: unknown) => {\n this.report(TASK_EVENT.delegationStartFailed, error, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: event.requestId,\n });\n });\n }\n\n private handleUpdate(event: DelegationUpdate): void {\n const existing = this.progress.get(event.requestId);\n if (!existing) return;\n\n const observedAt = this.nowMs();\n const currentElapsed = DelegationManager.elapsedMs(existing, observedAt);\n const hasDuration = event.durationMs !== undefined;\n this.progress.set(event.requestId, {\n // Spread, not field-by-field: anything carried on progress that this\n // event does not report (the assign-time context shape) must survive the\n // first update, or the completion event reports it as absent.\n ...existing,\n currentTool: event.currentTool ?? existing.currentTool,\n toolCount:\n event.toolCount === undefined ? existing.toolCount : Math.max(existing.toolCount ?? 0, event.toolCount),\n tokens: event.tokens === undefined ? existing.tokens : Math.max(existing.tokens ?? 0, event.tokens),\n durationMs: hasDuration ? Math.max(currentElapsed, event.durationMs!) : existing.durationMs,\n durationObservedAt: hasDuration ? observedAt : existing.durationObservedAt,\n });\n this.options.onChange?.();\n }\n\n private async handleResponse(event: DelegationResult): Promise<void> {\n if (!this.pendingTasks.has(event.requestId)) return;\n\n const succeeded = event.status === COMPLETED_STATE && !event.error;\n const state = succeeded ? COMPLETED_STATE : event.status === CANCELLED_STATE ? CANCELLED_STATE : FAILED_STATE;\n await this.settle(event.requestId, state, {\n status: event.status,\n error: event.error,\n output: truncate(event.output),\n outputPath: event.outputPath,\n sessionFile: event.sessionFile,\n durationMs: event.durationMs,\n toolCount: event.toolCount,\n });\n }\n\n /**\n * Apply the terminal state of a delegation and tell the model about it.\n *\n * A cancelled run returns the task to `pending` (the work is still wanted,\n * just not by that agent); a failure marks it `failed` so it stays visible\n * rather than silently rejoining the backlog.\n *\n * The request is claimed in `settlingRequests` while it remains published as\n * active work. It is removed only after the terminal state and model notification\n * have been handed off, so an auto-stop observer cannot end the session between\n * receiving the result and delivering it to the model.\n */\n private async settle(requestId: string, state: SettlementState, result: TaskDelegation['result']): Promise<void> {\n const pending = this.pendingTasks.get(requestId);\n if (!pending || this.settlingRequests.has(requestId)) return;\n this.settlingRequests.add(requestId);\n this.clearTimer(requestId);\n const { taskId } = pending;\n const progress = this.progress.get(requestId);\n\n try {\n const endedAt = this.now();\n let task: Task | undefined;\n try {\n const { value } = await this.options.store.mutate((document) =>\n this.patchDelegation(document, requestId, (current, delegation) => ({\n ...current,\n status: state === COMPLETED_STATE ? COMPLETED_STATE : state === CANCELLED_STATE ? 'pending' : FAILED_STATE,\n updatedAt: endedAt,\n delegation: { ...delegation, state, endedAt, ...(result ? { result } : {}) },\n })),\n );\n task = value;\n } catch (error) {\n this.report(TASK_EVENT.delegationSettleFailed, error, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n });\n }\n\n const agent = task?.delegation?.agent ?? progress?.agent ?? 'subagent';\n const subject = task?.subject ?? `#${taskId}`;\n\n // Repeats the assign-time context shape so the cost question (\"did packs\n // reduce child tool calls?\") is one grouping rather than a self-join.\n // A run that never started reports neither metric, keeping the medians clean.\n this.options.report?.event(TASK_EVENT.delegationCompleted, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n [AGENT_ATTRIBUTE]: agent,\n [OUTCOME_ATTRIBUTE]: state,\n [CONTEXT_PRESENT_ATTRIBUTE]: (progress?.contextFileCount ?? 0) > 0 || (progress?.contextNotesLength ?? 0) > 0,\n [CONTEXT_FILE_COUNT_ATTRIBUTE]: progress?.contextFileCount ?? 0,\n [CONTEXT_NOTES_LENGTH_ATTRIBUTE]: progress?.contextNotesLength ?? 0,\n ...(result?.toolCount === undefined ? {} : { [TOOL_COUNT_ATTRIBUTE]: result.toolCount }),\n ...(result?.durationMs === undefined ? {} : { [DURATION_MS_ATTRIBUTE]: result.durationMs }),\n });\n const listComplete =\n state === COMPLETED_STATE && task !== undefined && isTaskListComplete(this.options.store.snapshot.tasks);\n this.notifyModel(state, taskId, subject, agent, result, listComplete);\n } finally {\n this.pendingTasks.delete(requestId);\n this.progress.delete(requestId);\n this.settlingRequests.delete(requestId);\n this.options.onChange?.();\n }\n }\n\n private notifyModel(\n state: SettlementState,\n taskId: number,\n subject: string,\n agent: string,\n result: TaskDelegation['result'],\n listComplete: boolean,\n ): void {\n const notify = this.options.notify;\n if (!notify) return;\n\n const headline =\n state === COMPLETED_STATE\n ? `Subagent ${agent} completed task #${taskId}: ${subject}`\n : state === CANCELLED_STATE\n ? `Subagent ${agent} was cancelled on task #${taskId}: ${subject} (returned to pending)`\n : `Subagent ${agent} failed task #${taskId}: ${subject}`;\n\n const lines = [headline];\n if (listComplete) {\n lines.push(\n '',\n 'All tasks are completed. Review the full task list once more, then close it with task {\"action\":\"clear\"}.',\n );\n }\n if (result?.error) lines.push(`Error: ${result.error}`);\n if (result?.output) lines.push('', result.output);\n if (result?.outputPath) lines.push('', `Full output: ${result.outputPath}`);\n\n try {\n notify(\n { customType: NOTIFY_CUSTOM_TYPE, content: lines.join('\\n'), display: true },\n { triggerTurn: true, deliverAs: 'steer' },\n );\n } catch (error) {\n // The delegation state is already committed to the store, so a failed\n // notification costs the model its wake-up, not the result. Report it\n // rather than rethrowing, which would strand the settled run.\n this.options.onNotifyError(error, taskId);\n }\n }\n\n /**\n * Rewrite the task carrying `requestId`, returning the updated task as the mutation value.\n *\n * Terminal delegations are left alone. The document here is the freshest one,\n * read under the store lock, which is the only place the check is meaningful:\n * a `started` event can land after a cancel already settled the run, and\n * without this guard its write would resurrect a delegation that nothing is\n * tracking any more.\n */\n private patchDelegation(\n document: TaskDocument,\n requestId: string,\n patch: (task: Task, delegation: TaskDelegation) => Task,\n ): { document?: TaskDocument; value: Task | undefined } {\n const index = document.tasks.findIndex((task) => task.delegation?.requestId === requestId);\n if (index === -1) return { value: undefined };\n\n const task = document.tasks[index];\n if (!isDelegationActive(task)) return { value: task };\n\n const updated = patch(task, task.delegation!);\n if (updated === task) return { value: task };\n const tasks = [...document.tasks];\n tasks[index] = updated;\n return { document: { ...document, tasks }, value: updated };\n }\n\n dispose(): void {\n this.unbind();\n this.reset();\n }\n\n /** Clear one Pi session's transient delegation state without losing service injection. */\n reset(): void {\n const changed = this.pendingTasks.size > 0 || this.progress.size > 0;\n for (const timer of this.timers.values()) clearTimeout(timer);\n this.timers.clear();\n this.pendingTasks.clear();\n this.settlingRequests.clear();\n this.progress.clear();\n if (changed) this.options.onChange?.();\n }\n}\n"],"mappings":";;;;;;;AAuBA,MAAa,qBAAqB;AAClC,MAAa,2BAA2B;AAExC,MAAM,6BAA6B;AACnC,MAAM,yBAAyB;AAC/B,MAAM,4BAA4B;AAClC,MAAM,2BAA2B;AACjC,MAAM,oBAAoB;;;;;AAK1B,MAAM,kBAAkB;AACxB,MAAM,kBAAkB;AACxB,MAAM,eAAe;AACrB,MAAM,kBAAkB;AACxB,MAAM,mBAAmB;AACzB,MAAM,iBAAiC;AAEvC,MAAM,oBAAoB;AAC1B,MAAM,uBAAuB;AAG7B,MAAM,kBAAkB;AACxB,MAAM,gBAAgB;AACtB,MAAM,4BAA4B;AAClC,MAAM,+BAA+B;AACrC,MAAM,iCAAiC;AACvC,MAAM,yBAAyB;AAC/B,MAAM,uBAAuB;AAC7B,MAAM,wBAAwB;AAC9B,MA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A,EAAU;EAE5C,MAAM,OAAO,SAAS,MAAM;EAC5B,IAAI,CAAC,mBAAmB,IAAI,GAAG,OAAO,EAAE,OAAO,KAAK;EAEpD,MAAM,UAAU,MAAM,MAAM,KAAK,UAAW;EAC5C,IAAI,YAAY,MAAM,OAAO,EAAE,OAAO,KAAK;EAC3C,MAAM,QAAQ,CAAC,GAAG,SAAS,KAAK;EAChC,MAAM,SAAS;EACf,OAAO;GAAE,UAAU;IAAE,GAAG;IAAU;GAAM;GAAG,OAAO;EAAQ;CAC5D;CAEA,UAAgB;EACd,KAAK,OAAO;EACZ,KAAK,MAAM;CACb;;CAGA,QAAc;EACZ,MAAM,UAAU,KAAK,aAAa,OAAO,KAAK,KAAK,SAAS,OAAO;EACnE,KAAK,MAAM,SAAS,KAAK,OAAO,OAAO,GAAG,aAAa,KAAK;EAC5D,KAAK,OAAO,MAAM;EAClB,KAAK,aAAa,MAAM;EACxB,KAAK,iBAAiB,MAAM;EAC5B,KAAK,SAAS,MAAM;EACpB,IAAI,SAAS,KAAK,QAAQ,WAAW;CACvC;AACF"}
@@ -340,7 +340,7 @@ var DelegationManager = class DelegationManager {
340
340
  };
341
341
  }
342
342
  async cancel(taskId) {
343
- const task = this.options.store.read().tasks.find((candidate) => candidate.id === taskId);
343
+ const task = (await this.options.store.readAsync()).tasks.find((candidate) => candidate.id === taskId);
344
344
  if (!task) return {
345
345
  ok: false,
346
346
  message: `#${taskId} not found`
@@ -457,7 +457,8 @@ var DelegationManager = class DelegationManager {
457
457
  ...delegation,
458
458
  state: "running",
459
459
  startedAt: delegation.startedAt ?? this.now(),
460
- ...runId ? { runId } : {}
460
+ ...runId ? { runId } : {},
461
+ ...event.identity ? { identity: event.identity } : {}
461
462
  }
462
463
  }))).then(() => this.options.onChange?.()).catch((error) => {
463
464
  this.report(require_telemetry.TASK_EVENT.delegationStartFailed, error, {
@@ -658,4 +659,4 @@ Object.defineProperty(exports, "NOTIFY_CUSTOM_TYPE", {
658
659
  }
659
660
  });
660
661
 
661
- //# sourceMappingURL=delegation-frvEXhIz.cjs.map
662
+ //# sourceMappingURL=delegation-BJtAUTVg.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"delegation-BJtAUTVg.cjs","names":["PO_DELEGATION_ACCEPTED_EVENT","PO_DELEGATION_STARTED_EVENT","PO_DELEGATION_UPDATED_EVENT","PO_DELEGATION_FINISHED_EVENT","TASK_EVENT","reconcileOrphanedDelegations","isDelegationActive","isBlocked","isTaskListComplete"],"sources":["../src/services/delegation/index.ts"],"sourcesContent":["import {\n type DelegationAccepted as DelegationAcceptedPayload,\n PO_DELEGATION_ACCEPTED_EVENT,\n PO_DELEGATION_FINISHED_EVENT,\n PO_DELEGATION_STARTED_EVENT,\n PO_DELEGATION_UPDATED_EVENT,\n type PoDelegationService,\n type DelegationResult,\n type DelegationStarted as DelegationStartedPayload,\n type DelegationUpdate,\n type InlineAgent,\n} from '@agimon-ai/po-core/delegation';\nimport type { Context } from '@deepseek-ai/cordis';\n\nimport { isBlocked, isTaskListComplete } from '../../models/taskGraph';\nimport { MAX_BRIEF_FILES } from '../../types/delegation';\nimport { TASK_EVENT, type TaskEventName, type TaskFailureReporter } from '../../types/telemetry';\nimport { reconcileOrphanedDelegations } from '../reconcile';\nimport type { TaskStore } from '../taskStore';\n\nexport { MAX_BRIEF_FILES };\nimport { isDelegationActive, type Task, type TaskDelegation, type TaskDocument } from '../../models/task';\n\nexport const NOTIFY_CUSTOM_TYPE = 'po-task-notify';\nexport const BACKGROUND_WORK_PROVIDER = 'po-task';\n\nconst DEFAULT_STARTED_TIMEOUT_MS = 5000;\nconst DEFAULT_RUN_TIMEOUT_MS = 20 * 60 * 1000;\nconst DEFAULT_CANCEL_TIMEOUT_MS = 10_000;\nconst MAX_RUN_TIMEOUT_GRACE_MS = 60_000;\nconst MAX_STORED_OUTPUT = 4000;\n/**\n * Cap on files rendered into a brief. Exported so the tool schema can state the\n * same number to the model rather than restating it and drifting.\n */\nconst MAX_BRIEF_NOTES = 1500;\nconst COMPLETED_STATE = 'completed';\nconst FAILED_STATE = 'failed';\nconst CANCELLED_STATE = 'cancelled';\nconst TIMED_OUT_STATUS = 'timed_out';\nconst DELETED_STATUS: Task['status'] = 'deleted';\n\nconst TASK_ID_ATTRIBUTE = 'task.id';\nconst REQUEST_ID_ATTRIBUTE = 'delegation.request_id';\n// `_name` suffix is load-bearing: the telemetry redactor drops string values\n// whose key has no safe meaning, and a bare `delegation.agent` is dropped.\nconst AGENT_ATTRIBUTE = 'delegation.agent_name';\nconst PID_ATTRIBUTE = 'delegation.pid';\nconst CONTEXT_PRESENT_ATTRIBUTE = 'delegation.context_present';\nconst CONTEXT_FILE_COUNT_ATTRIBUTE = 'delegation.context_file_count';\nconst CONTEXT_NOTES_LENGTH_ATTRIBUTE = 'delegation.context_notes_length';\nconst BRIEF_LENGTH_ATTRIBUTE = 'delegation.brief_length';\nconst TOOL_COUNT_ATTRIBUTE = 'delegation.tool_count';\nconst DURATION_MS_ATTRIBUTE = 'delegation.duration_ms';\nconst OUTCOME_ATTRIBUTE = 'delegation.outcome';\n\ntype SettlementState = typeof COMPLETED_STATE | typeof FAILED_STATE | typeof CANCELLED_STATE;\n\nexport const ERR_NO_RUNTIME =\n 'No subagent runtime responded. Delegation needs the subagents extension — relaunch po with agents enabled.';\nexport const ERR_CHILD_SESSION =\n 'assign is only available in the main session. Update this task directly instead of re-delegating it.';\nexport const ERR_CANCEL_UNACKNOWLEDGED = 'Subagent did not acknowledge the cancel request';\n\n/** Live progress from a running subagent. Kept in memory: persisting per-tool\n * ticks would rewrite the store file every second for no durable benefit. */\nexport interface DelegationProgress {\n agent: string;\n currentTool?: string;\n toolCount?: number;\n tokens?: number;\n /** Latest child-runtime duration baseline, excluding assignment wait. */\n durationMs?: number;\n /** Wall-clock time at which durationMs was observed or rebased. */\n durationObservedAt?: number;\n /** Assign-time context-pack shape, carried so the completion event can be\n * grouped by it without joining back to the assignment event. */\n contextFileCount?: number;\n contextNotesLength?: number;\n}\n\nexport type DelegationNotifier = (\n message: { customType: string; content: string; display: boolean },\n options?: { triggerTurn?: boolean; deliverAs?: 'steer' | 'followUp' | 'nextTurn' },\n) => void;\n\nexport interface DelegationPlatform {\n readonly environment: Readonly<Record<string, string | undefined>>;\n readonly processId: number;\n readonly createRequestId: () => string;\n readonly formatBriefPath: (entry: string, cwd: string) => string;\n}\n\nexport interface DelegationManagerOptions {\n store: TaskStore;\n cwd: string;\n platform: DelegationPlatform;\n notify?: DelegationNotifier;\n getSessionId?: () => string | undefined;\n onChange?: () => void;\n startedTimeoutMs?: number;\n /** How long a started run may go without reporting a result. */\n runTimeoutMs?: number;\n /** How long to wait for a cancelled run to report back before forcing it. */\n cancelTimeoutMs?: number;\n now?: () => string;\n nowMs?: () => number;\n /** Called when a completion notification could not be delivered. */\n onNotifyError: (error: unknown, taskId: number) => void;\n /** Where other swallowed delegation failures go. */\n report?: TaskFailureReporter;\n}\n\nexport interface AssignOptions {\n agent?: string;\n inlineAgent?: InlineAgent;\n instructions?: string;\n /** Paths the parent already located, rendered into the brief so the child\n * skips rediscovering them. */\n relevantFiles?: string[];\n /** Facts the parent already established, rendered into the brief so the child\n * does not re-derive them. */\n priorFindings?: string;\n model?: string;\n context?: 'fresh' | 'fork';\n signal?: AbortSignal;\n}\n\nexport interface DelegationOutcome {\n ok: boolean;\n message: string;\n}\n\n/** Result of the guarded store mutation that claims a task for delegation. */\ninterface AssignAttempt extends DelegationOutcome {\n task?: Task;\n}\n\ninterface PendingTask {\n readonly taskId: number;\n readonly sessionId?: string;\n}\n\nfunction truncate(value: string | undefined, limit = MAX_STORED_OUTPUT): string | undefined {\n if (!value) return undefined;\n return value.length <= limit ? value : `${value.slice(0, limit)}\\n… (truncated)`;\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/** The assign-time context pack, normalized once for the brief and the telemetry. */\ninterface BriefContext {\n files: string[];\n notes?: string;\n}\n\n/** Normalize the parent context with host-owned path semantics. */\nfunction briefContext(options: AssignOptions, cwd: string, platform: DelegationPlatform): BriefContext {\n const files = new Set<string>();\n for (const entry of options.relevantFiles ?? []) {\n if (files.size >= MAX_BRIEF_FILES) break;\n const normalized = platform.formatBriefPath(entry.trim(), cwd);\n if (normalized && normalized !== '.') files.add(normalized);\n }\n return { files: [...files], notes: truncate(options.priorFindings?.trim(), MAX_BRIEF_NOTES) };\n}\n\n/**\n * Build the brief handed to the subagent.\n *\n * Po Team owns the child tool surface and the parent owns the task record.\n * Keeping those responsibilities explicit prevents a child from attempting to\n * call a task tool that is not loaded in its runtime, while still giving it a\n * reliable path to ask the parent for a decision.\n *\n * The context pack is the parent's verified discovery handed over. The whole\n * block is omitted when nothing was supplied: this brief is the child's whole\n * starting context, so an empty section header is pure token cost.\n */\nfunction buildBrief(task: Task, instructions: string | undefined, context: BriefContext): string {\n const sections = [`Task #${task.id}: ${task.subject}`];\n if (task.description) sections.push(task.description);\n if (instructions) sections.push(instructions);\n if (context.files.length > 0 || context.notes) {\n const contextLines = ['Parent context — consume before repository discovery:'];\n if (context.files.length > 0) {\n contextLines.push(`- Parent-verified files (read these first with direct reads): ${context.files.join(', ')}`);\n }\n if (context.notes) {\n contextLines.push(\n `- Established facts (do not re-derive unless direct evidence contradicts them): ${context.notes}`,\n );\n }\n contextLines.push(\n 'This pack satisfies initial repository/context exploration. Do not begin with repository-wide listing, find, or grep. Expand only after consuming the pack and naming a concrete missing dependency or invalid path; search narrowly for that item and state why.',\n );\n sections.push(contextLines.join('\\n'));\n }\n sections.push(\n 'Coordination: work directly without changing the task record; ask main through intercom only for blockers or decisions; report changed files and verification when done.',\n );\n return sections.join('\\n\\n');\n}\n\n/**\n * Owns the lifecycle of tasks delegated to subagents.\n *\n * Delegation rides Team's injected Cordis service rather than spawning\n * processes directly, so po-task stays decoupled from the subagent runtime\n * and degrades to a clear error when that service is not loaded.\n *\n * Liveness rule: every entry in `pendingTasks` has a timer armed against it, so\n * a delegation always has a deadline no matter which phase it is in. Losing\n * that pairing is what previously left tasks running forever.\n */\nexport class DelegationManager {\n private readonly options: DelegationManagerOptions;\n private readonly progress = new Map<string, DelegationProgress>();\n private readonly pendingTasks = new Map<string, PendingTask>();\n private readonly settlingRequests = new Set<string>();\n private readonly timers = new Map<string, ReturnType<typeof setTimeout>>();\n private readonly subscriptions: Array<() => void> = [];\n private service: PoDelegationService | undefined;\n\n constructor(options: DelegationManagerOptions) {\n this.options = options;\n }\n\n setCwd(cwd: string): void {\n this.options.cwd = cwd;\n }\n\n private now(): string {\n return this.options.now?.() ?? new Date().toISOString();\n }\n\n private nowMs(): number {\n return this.options.nowMs?.() ?? Date.now();\n }\n\n private get runTimeoutMs(): number {\n return this.options.runTimeoutMs ?? DEFAULT_RUN_TIMEOUT_MS;\n }\n\n private report(event: TaskEventName, error: unknown, attributes?: Record<string, string | number | boolean>): void {\n this.options.report?.error(event, error, attributes);\n }\n\n /** True in a session that is itself a subagent child. */\n get isChildSession(): boolean {\n return Boolean(this.options.platform.environment.PI_SUBAGENT_CHILD);\n }\n\n /** Live progress for a task, for the overlay to render. */\n progressFor(task: Task): DelegationProgress | undefined {\n const requestId = task.delegation?.requestId;\n return requestId ? this.progress.get(requestId) : undefined;\n }\n\n /** Displayed runtime duration, rebased from the latest child observation. */\n static elapsedMs(progress: DelegationProgress, nowMs = Date.now()): number {\n const baseline = progress.durationMs ?? 0;\n const observedAt = progress.durationObservedAt ?? nowMs;\n return baseline + Math.max(0, nowMs - observedAt);\n }\n\n /** Rebind to the active Team service without stacking lifecycle listeners. */\n bind(ctx: Context, service: PoDelegationService): () => void {\n this.unbind();\n this.service = service;\n this.subscriptions.push(\n ctx.on(PO_DELEGATION_ACCEPTED_EVENT, (event) => {\n this.handleAccepted(event);\n }),\n ctx.on(PO_DELEGATION_STARTED_EVENT, (event) => {\n this.handleStarted(event);\n }),\n ctx.on(PO_DELEGATION_UPDATED_EVENT, (event) => {\n this.handleUpdate(event);\n }),\n ctx.on(PO_DELEGATION_FINISHED_EVENT, (event) => {\n void this.handleResponse(event).catch((error: unknown) => {\n this.report(TASK_EVENT.delegationResponseFailed, error, { [REQUEST_ID_ATTRIBUTE]: event.requestId });\n });\n }),\n );\n return () => {\n if (this.service === service) this.unbind();\n };\n }\n\n /** Remove only the cross-package binding; task state and watchdogs remain live. */\n unbind(): void {\n for (const unsubscribe of this.subscriptions.splice(0)) unsubscribe();\n this.service = undefined;\n }\n\n /** Items still in flight, surfaced so auto-stop will not kill the harness. */\n listActiveWork(): Array<{ id: string; sessionId: string }> {\n return [...this.pendingTasks.entries()].flatMap(([requestId, pending]) =>\n pending.sessionId ? [{ id: `task-${pending.taskId}:${requestId}`, sessionId: pending.sessionId }] : [],\n );\n }\n\n /**\n * Return tasks nothing can finish to `pending`.\n *\n * The live request set is read inside the mutation so a delegation assigned\n * while the lock was contended is not mistaken for a leftover.\n */\n async reconcile(isCurrent: () => boolean = () => true): Promise<Task[]> {\n const { value } = await this.options.store.mutate((document) => {\n if (!isCurrent()) return { value: [] as Task[] };\n const result = reconcileOrphanedDelegations(document, this.now(), undefined, {\n pid: this.options.platform.processId,\n liveRequestIds: new Set(this.pendingTasks.keys()),\n });\n if (result.orphaned.length === 0) return { value: [] as Task[] };\n return { document: result.document, value: result.orphaned };\n });\n\n if (!isCurrent()) return [];\n for (const task of value) {\n this.options.report?.warn(TASK_EVENT.delegationOrphaned, new Error(task.delegation?.result?.error ?? ''), {\n [TASK_ID_ATTRIBUTE]: task.id,\n ...(task.delegation?.agent ? { [AGENT_ATTRIBUTE]: task.delegation.agent } : {}),\n ...(task.delegation?.pid === undefined ? {} : { [PID_ATTRIBUTE]: task.delegation.pid }),\n });\n }\n\n if (value.length > 0) this.options.onChange?.();\n return value;\n }\n\n async assign(taskId: number, options: AssignOptions): Promise<DelegationOutcome> {\n const agent = options.agent?.trim();\n if (!agent) return { ok: false, message: 'agent required for assign' };\n if (this.isChildSession) return { ok: false, message: ERR_CHILD_SESSION };\n if (options.signal?.aborted) return { ok: false, message: 'delegation cancelled before it started' };\n\n const requestId = this.options.platform.createRequestId();\n const startedAt = this.now();\n const sessionId = this.options.getSessionId?.();\n const context = briefContext(options, this.options.cwd, this.options.platform);\n\n const { value: outcome } = await this.options.store.mutate<AssignAttempt>((current) => {\n const index = current.tasks.findIndex((task) => task.id === taskId);\n if (index === -1) return { value: { ok: false, message: `#${taskId} not found` } };\n\n const task = current.tasks[index];\n if (task.status === DELETED_STATUS) return { value: { ok: false, message: `#${taskId} is deleted` } };\n if (task.status === COMPLETED_STATE) {\n return { value: { ok: false, message: `#${taskId} is already completed` } };\n }\n if (isDelegationActive(task)) {\n return { value: { ok: false, message: `#${taskId} is already delegated to ${task.delegation?.agent}` } };\n }\n if (isBlocked(current.tasks, task)) {\n const blockers = (task.blockedBy ?? []).map((id) => `#${id}`).join(', ');\n return { value: { ok: false, message: `#${taskId} is blocked by ${blockers}` } };\n }\n\n const delegation: TaskDelegation = {\n requestId,\n agent,\n state: 'requested',\n pid: this.options.platform.processId,\n startedAt,\n ...(sessionId ? { sessionId } : {}),\n ...(options.model ? { model: options.model } : {}),\n };\n\n const tasks = [...current.tasks];\n tasks[index] = { ...task, owner: agent, updatedAt: startedAt, delegation };\n return {\n document: { ...current, tasks },\n value: { ok: true, message: '', task: tasks[index] },\n };\n });\n\n if (!outcome.ok || !outcome.task) return { ok: false, message: outcome.message };\n\n const contextNotesLength = context.notes?.length ?? 0;\n this.pendingTasks.set(requestId, { taskId, sessionId });\n this.progress.set(requestId, { agent, contextFileCount: context.files.length, contextNotesLength });\n this.armStartedTimeout(requestId);\n this.options.onChange?.();\n const request = {\n requestId,\n taskId,\n agent,\n ...(options.inlineAgent ? { inlineAgent: options.inlineAgent } : {}),\n prompt: buildBrief(outcome.task, options.instructions, context),\n ...(options.context ? { context: options.context } : {}),\n cwd: this.options.cwd,\n artifacts: true,\n timeoutMs: this.runTimeoutMs,\n runMode: 'detached' as const,\n teamTask: { id: String(outcome.task.id), subject: outcome.task.subject },\n ...(options.model ? { model: options.model } : {}),\n };\n\n try {\n const service = this.service;\n if (!service) throw new Error(ERR_NO_RUNTIME);\n void service.request(request).catch((error: unknown) => {\n this.report(TASK_EVENT.delegationRequestFailed, error, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n [AGENT_ATTRIBUTE]: agent,\n });\n this.settleDetached(requestId, FAILED_STATE, {\n status: FAILED_STATE,\n error: `Delegation request failed: ${messageOf(error)}`,\n });\n });\n } catch (error) {\n this.report(TASK_EVENT.delegationRequestFailed, error, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n [AGENT_ATTRIBUTE]: agent,\n });\n const detail = messageOf(error);\n await this.settle(requestId, FAILED_STATE, {\n status: FAILED_STATE,\n error: `Delegation request failed: ${detail}`,\n });\n return { ok: false, message: `Could not dispatch #${taskId} to ${agent}: ${detail}` };\n }\n\n // Recorded only after the service accepted the request call, so it means a\n // brief actually entered Team's state machine rather than merely being assembled.\n this.options.report?.event(TASK_EVENT.delegationAssigned, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n [AGENT_ATTRIBUTE]: agent,\n [CONTEXT_PRESENT_ATTRIBUTE]: context.files.length > 0 || contextNotesLength > 0,\n [CONTEXT_FILE_COUNT_ATTRIBUTE]: context.files.length,\n [CONTEXT_NOTES_LENGTH_ATTRIBUTE]: contextNotesLength,\n [BRIEF_LENGTH_ATTRIBUTE]: request.prompt.length,\n });\n\n return {\n ok: true,\n message: `Delegated #${taskId} to ${agent} in the background. It runs independently of this turn and will notify you when it finishes. Continue non-overlapping work, or end your turn.`,\n };\n }\n\n async cancel(taskId: number): Promise<DelegationOutcome> {\n const document = await this.options.store.readAsync();\n const task = document.tasks.find((candidate) => candidate.id === taskId);\n if (!task) return { ok: false, message: `#${taskId} not found` };\n if (!task.delegation || !isDelegationActive(task)) {\n return { ok: false, message: `#${taskId} has no running delegation` };\n }\n\n const { requestId } = task.delegation;\n this.service?.cancel({ requestId });\n // Only this session can force the outcome; a delegation owned elsewhere\n // gets the request and nothing more.\n this.armCancelTimeout(requestId);\n return { ok: true, message: `Cancelling delegation for #${taskId} (${task.delegation.agent})` };\n }\n\n /** Settle without awaiting, reporting rather than dropping a failure. */\n private settleDetached(\n requestId: string,\n state: SettlementState,\n result: TaskDelegation['result'],\n event: TaskEventName = TASK_EVENT.delegationSettleFailed,\n ): void {\n void this.settle(requestId, state, result).catch((error: unknown) => {\n this.report(event, error, { [REQUEST_ID_ATTRIBUTE]: requestId });\n });\n }\n\n /**\n * Fail a delegation that nobody acknowledged.\n *\n * Provider loss or a stalled Team runtime can still leave a dispatched\n * request silent. Without this acknowledgement deadline the task would sit\n * in `requested` forever.\n */\n private armStartedTimeout(requestId: string): void {\n this.armTimer(requestId, this.options.startedTimeoutMs ?? DEFAULT_STARTED_TIMEOUT_MS, () => {\n this.settleDetached(requestId, FAILED_STATE, { status: FAILED_STATE, error: ERR_NO_RUNTIME });\n });\n }\n\n /**\n * Bound a run that already started.\n *\n * The request carries the same budget, so in the normal case the runtime ends\n * the run itself and reports a richer result. The grace period biases toward\n * that answer; this timer only covers a runtime that goes silent, which is\n * precisely the case where no response event will ever arrive.\n */\n private armRunTimeout(requestId: string): void {\n const grace = Math.min(MAX_RUN_TIMEOUT_GRACE_MS, this.runTimeoutMs);\n this.armTimer(requestId, this.runTimeoutMs + grace, () => {\n const taskId = this.pendingTasks.get(requestId)?.taskId;\n const agent = this.progress.get(requestId)?.agent;\n const error = new Error(`Delegation produced no result within ${this.runTimeoutMs}ms`);\n this.options.report?.warn(TASK_EVENT.delegationTimedOut, error, {\n ...(taskId === undefined ? {} : { [TASK_ID_ATTRIBUTE]: taskId }),\n [REQUEST_ID_ATTRIBUTE]: requestId,\n ...(agent ? { [AGENT_ATTRIBUTE]: agent } : {}),\n });\n this.service?.cancel({ requestId, reason: error.message });\n this.settleDetached(requestId, FAILED_STATE, { status: TIMED_OUT_STATUS, error: error.message });\n });\n }\n\n /**\n * Guarantee a cancel reaches a terminal state.\n *\n * Calling the service is a request, not an outcome: a runtime that has\n * already forgotten the request answers nothing at all. The window still\n * favours a real response, which carries the run's partial output.\n */\n private armCancelTimeout(requestId: string): void {\n if (!this.pendingTasks.has(requestId)) return;\n this.armTimer(requestId, this.options.cancelTimeoutMs ?? DEFAULT_CANCEL_TIMEOUT_MS, () => {\n this.settleDetached(requestId, CANCELLED_STATE, {\n status: CANCELLED_STATE,\n error: ERR_CANCEL_UNACKNOWLEDGED,\n });\n });\n }\n\n private armTimer(requestId: string, delayMs: number, onFire: () => void): void {\n this.clearTimer(requestId);\n const timer = setTimeout(onFire, delayMs);\n timer.unref?.();\n this.timers.set(requestId, timer);\n }\n\n private clearTimer(requestId: string): void {\n const timer = this.timers.get(requestId);\n if (timer) clearTimeout(timer);\n this.timers.delete(requestId);\n }\n\n /** Runtime acknowledgement moves the request off the short extension-presence watchdog while launch is in flight. */\n private handleAccepted(event: DelegationAcceptedPayload): void {\n if (!this.pendingTasks.has(event.requestId)) return;\n this.armRunTimeout(event.requestId);\n }\n\n private handleStarted(event: DelegationStartedPayload): void {\n const { runId } = event;\n const taskId = this.pendingTasks.get(event.requestId)?.taskId;\n if (taskId === undefined) return;\n this.armRunTimeout(event.requestId);\n const existing = this.progress.get(event.requestId);\n if (existing) {\n this.progress.set(event.requestId, {\n ...existing,\n durationMs: existing.durationMs ?? 0,\n durationObservedAt: existing.durationObservedAt ?? this.nowMs(),\n });\n }\n\n void this.options.store\n .mutate((document) =>\n this.patchDelegation(document, event.requestId, (task, delegation) => ({\n ...task,\n status: task.status === COMPLETED_STATE ? task.status : 'in_progress',\n delegation: {\n ...delegation,\n state: 'running',\n startedAt: delegation.startedAt ?? this.now(),\n ...(runId ? { runId } : {}),\n ...(event.identity ? { identity: event.identity } : {}),\n },\n })),\n )\n .then(() => this.options.onChange?.())\n .catch((error: unknown) => {\n this.report(TASK_EVENT.delegationStartFailed, error, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: event.requestId,\n });\n });\n }\n\n private handleUpdate(event: DelegationUpdate): void {\n const existing = this.progress.get(event.requestId);\n if (!existing) return;\n\n const observedAt = this.nowMs();\n const currentElapsed = DelegationManager.elapsedMs(existing, observedAt);\n const hasDuration = event.durationMs !== undefined;\n this.progress.set(event.requestId, {\n // Spread, not field-by-field: anything carried on progress that this\n // event does not report (the assign-time context shape) must survive the\n // first update, or the completion event reports it as absent.\n ...existing,\n currentTool: event.currentTool ?? existing.currentTool,\n toolCount:\n event.toolCount === undefined ? existing.toolCount : Math.max(existing.toolCount ?? 0, event.toolCount),\n tokens: event.tokens === undefined ? existing.tokens : Math.max(existing.tokens ?? 0, event.tokens),\n durationMs: hasDuration ? Math.max(currentElapsed, event.durationMs!) : existing.durationMs,\n durationObservedAt: hasDuration ? observedAt : existing.durationObservedAt,\n });\n this.options.onChange?.();\n }\n\n private async handleResponse(event: DelegationResult): Promise<void> {\n if (!this.pendingTasks.has(event.requestId)) return;\n\n const succeeded = event.status === COMPLETED_STATE && !event.error;\n const state = succeeded ? COMPLETED_STATE : event.status === CANCELLED_STATE ? CANCELLED_STATE : FAILED_STATE;\n await this.settle(event.requestId, state, {\n status: event.status,\n error: event.error,\n output: truncate(event.output),\n outputPath: event.outputPath,\n sessionFile: event.sessionFile,\n durationMs: event.durationMs,\n toolCount: event.toolCount,\n });\n }\n\n /**\n * Apply the terminal state of a delegation and tell the model about it.\n *\n * A cancelled run returns the task to `pending` (the work is still wanted,\n * just not by that agent); a failure marks it `failed` so it stays visible\n * rather than silently rejoining the backlog.\n *\n * The request is claimed in `settlingRequests` while it remains published as\n * active work. It is removed only after the terminal state and model notification\n * have been handed off, so an auto-stop observer cannot end the session between\n * receiving the result and delivering it to the model.\n */\n private async settle(requestId: string, state: SettlementState, result: TaskDelegation['result']): Promise<void> {\n const pending = this.pendingTasks.get(requestId);\n if (!pending || this.settlingRequests.has(requestId)) return;\n this.settlingRequests.add(requestId);\n this.clearTimer(requestId);\n const { taskId } = pending;\n const progress = this.progress.get(requestId);\n\n try {\n const endedAt = this.now();\n let task: Task | undefined;\n try {\n const { value } = await this.options.store.mutate((document) =>\n this.patchDelegation(document, requestId, (current, delegation) => ({\n ...current,\n status: state === COMPLETED_STATE ? COMPLETED_STATE : state === CANCELLED_STATE ? 'pending' : FAILED_STATE,\n updatedAt: endedAt,\n delegation: { ...delegation, state, endedAt, ...(result ? { result } : {}) },\n })),\n );\n task = value;\n } catch (error) {\n this.report(TASK_EVENT.delegationSettleFailed, error, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n });\n }\n\n const agent = task?.delegation?.agent ?? progress?.agent ?? 'subagent';\n const subject = task?.subject ?? `#${taskId}`;\n\n // Repeats the assign-time context shape so the cost question (\"did packs\n // reduce child tool calls?\") is one grouping rather than a self-join.\n // A run that never started reports neither metric, keeping the medians clean.\n this.options.report?.event(TASK_EVENT.delegationCompleted, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n [AGENT_ATTRIBUTE]: agent,\n [OUTCOME_ATTRIBUTE]: state,\n [CONTEXT_PRESENT_ATTRIBUTE]: (progress?.contextFileCount ?? 0) > 0 || (progress?.contextNotesLength ?? 0) > 0,\n [CONTEXT_FILE_COUNT_ATTRIBUTE]: progress?.contextFileCount ?? 0,\n [CONTEXT_NOTES_LENGTH_ATTRIBUTE]: progress?.contextNotesLength ?? 0,\n ...(result?.toolCount === undefined ? {} : { [TOOL_COUNT_ATTRIBUTE]: result.toolCount }),\n ...(result?.durationMs === undefined ? {} : { [DURATION_MS_ATTRIBUTE]: result.durationMs }),\n });\n const listComplete =\n state === COMPLETED_STATE && task !== undefined && isTaskListComplete(this.options.store.snapshot.tasks);\n this.notifyModel(state, taskId, subject, agent, result, listComplete);\n } finally {\n this.pendingTasks.delete(requestId);\n this.progress.delete(requestId);\n this.settlingRequests.delete(requestId);\n this.options.onChange?.();\n }\n }\n\n private notifyModel(\n state: SettlementState,\n taskId: number,\n subject: string,\n agent: string,\n result: TaskDelegation['result'],\n listComplete: boolean,\n ): void {\n const notify = this.options.notify;\n if (!notify) return;\n\n const headline =\n state === COMPLETED_STATE\n ? `Subagent ${agent} completed task #${taskId}: ${subject}`\n : state === CANCELLED_STATE\n ? `Subagent ${agent} was cancelled on task #${taskId}: ${subject} (returned to pending)`\n : `Subagent ${agent} failed task #${taskId}: ${subject}`;\n\n const lines = [headline];\n if (listComplete) {\n lines.push(\n '',\n 'All tasks are completed. Review the full task list once more, then close it with task {\"action\":\"clear\"}.',\n );\n }\n if (result?.error) lines.push(`Error: ${result.error}`);\n if (result?.output) lines.push('', result.output);\n if (result?.outputPath) lines.push('', `Full output: ${result.outputPath}`);\n\n try {\n notify(\n { customType: NOTIFY_CUSTOM_TYPE, content: lines.join('\\n'), display: true },\n { triggerTurn: true, deliverAs: 'steer' },\n );\n } catch (error) {\n // The delegation state is already committed to the store, so a failed\n // notification costs the model its wake-up, not the result. Report it\n // rather than rethrowing, which would strand the settled run.\n this.options.onNotifyError(error, taskId);\n }\n }\n\n /**\n * Rewrite the task carrying `requestId`, returning the updated task as the mutation value.\n *\n * Terminal delegations are left alone. The document here is the freshest one,\n * read under the store lock, which is the only place the check is meaningful:\n * a `started` event can land after a cancel already settled the run, and\n * without this guard its write would resurrect a delegation that nothing is\n * tracking any more.\n */\n private patchDelegation(\n document: TaskDocument,\n requestId: string,\n patch: (task: Task, delegation: TaskDelegation) => Task,\n ): { document?: TaskDocument; value: Task | undefined } {\n const index = document.tasks.findIndex((task) => task.delegation?.requestId === requestId);\n if (index === -1) return { value: undefined };\n\n const task = document.tasks[index];\n if (!isDelegationActive(task)) return { value: task };\n\n const updated = patch(task, task.delegation!);\n if (updated === task) return { value: task };\n const tasks = [...document.tasks];\n tasks[index] = updated;\n return { document: { ...document, tasks }, value: updated };\n }\n\n dispose(): void {\n this.unbind();\n this.reset();\n }\n\n /** Clear one Pi session's transient delegation state without losing service injection. */\n reset(): void {\n const changed = this.pendingTasks.size > 0 || this.progress.size > 0;\n for (const timer of this.timers.values()) clearTimeout(timer);\n this.timers.clear();\n this.pendingTasks.clear();\n this.settlingRequests.clear();\n this.progress.clear();\n if (changed) this.options.onChange?.();\n }\n}\n"],"mappings":";;;;;;;AAuBA,MAAa,qBAAqB;AAClC,MAAa,2BAA2B;AAExC,MAAM,6BAA6B;AACnC,MAAM,yBAAyB;AAC/B,MAAM,4BAA4B;AAClC,MAAM,2BAA2B;AACjC,MAAM,oBAAoB;;;;;AAK1B,MAAM,kBAAkB;AACxB,MAAM,kBAAkB;AACxB,MAAM,eAAe;AACrB,MAAM,kBAAkB;AACxB,MAAM,mBAAmB;AACzB,MAAM,iBAAiC;AAEvC,MAAM,oBAAoB;AAC1B,MAAM,uBAAuB;AAG7B,MAAM,kBAAkB;AACxB,MAAM,gBAAgB;AACtB,MAAM,4BAA4B;AAClC,MAAM,+BAA+B;AACrC,MAAM,iCAAiC;AACvC,MAAM,yBAAyB;AAC/B,MAAM,uBAAuB;AAC7B,MAAM,wBAAwB;AAC9B,MAAM,oBAAoB;AAI1B,MAAa,iBACX;AACF,MAAa,oBACX;AACF,MAAa,4BAA4B;AAiFzC,SAAS,SAAS,OAA2B,QAAQ,mBAAuC;CAC1F,IAAI,CAAC,OAAO,OAAO,KAAA;CACnB,OAAO,MAAM,UAAU,QAAQ,QAAQ,GAAG,MAAM,MAAM,GAAG,KAAK,EAAE;AAClE;AAEA,SAAS,UAAU,OAAwB;CACzC,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;;AASA,SAAS,aAAa,SAAwB,KAAa,UAA4C;CACrG,MAAM,wBAAQ,IAAI,IAAY;CAC9B,KAAK,MAAM,SAAS,QAAQ,iBAAiB,CAAC,GAAG;EAC/C,IAAI,MAAM,QAAA,IAAyB;EACnC,MAAM,aAAa,SAAS,gBAAgB,MAAM,KAAK,GAAG,GAAG;E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gB;EACd,KAAK,OAAO;EACZ,KAAK,MAAM;CACb;;CAGA,QAAc;EACZ,MAAM,UAAU,KAAK,aAAa,OAAO,KAAK,KAAK,SAAS,OAAO;EACnE,KAAK,MAAM,SAAS,KAAK,OAAO,OAAO,GAAG,aAAa,KAAK;EAC5D,KAAK,OAAO,MAAM;EAClB,KAAK,aAAa,MAAM;EACxB,KAAK,iBAAiB,MAAM;EAC5B,KAAK,SAAS,MAAM;EACpB,IAAI,SAAS,KAAK,QAAQ,WAAW;CACvC;AACF"}
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_delegation = require("./delegation-LDpHP2CC.cjs");
3
- const require_delegation$1 = require("./delegation-frvEXhIz.cjs");
3
+ const require_delegation$1 = require("./delegation-BJtAUTVg.cjs");
4
4
  exports.BACKGROUND_WORK_PROVIDER = require_delegation$1.BACKGROUND_WORK_PROVIDER;
5
5
  exports.DelegationManager = require_delegation$1.DelegationManager;
6
6
  exports.ERR_CANCEL_UNACKNOWLEDGED = require_delegation$1.ERR_CANCEL_UNACKNOWLEDGED;
@@ -1,2 +1,2 @@
1
- import { a as DelegationNotifier, c as DelegationProgress, d as ERR_NO_RUNTIME, f as NOTIFY_CUSTOM_TYPE, i as DelegationManagerOptions, l as ERR_CANCEL_UNACKNOWLEDGED, n as BACKGROUND_WORK_PROVIDER, o as DelegationOutcome, p as MAX_BRIEF_FILES, r as DelegationManager, s as DelegationPlatform, t as AssignOptions, u as ERR_CHILD_SESSION } from "./index-B9QNwUBr.mjs";
1
+ import { a as DelegationNotifier, c as DelegationProgress, d as ERR_NO_RUNTIME, f as NOTIFY_CUSTOM_TYPE, i as DelegationManagerOptions, l as ERR_CANCEL_UNACKNOWLEDGED, n as BACKGROUND_WORK_PROVIDER, o as DelegationOutcome, p as MAX_BRIEF_FILES, r as DelegationManager, s as DelegationPlatform, t as AssignOptions, u as ERR_CHILD_SESSION } from "./index-sahNy7Hg.mjs";
2
2
  export { AssignOptions, BACKGROUND_WORK_PROVIDER, DelegationManager, DelegationManagerOptions, DelegationNotifier, DelegationOutcome, DelegationPlatform, DelegationProgress, ERR_CANCEL_UNACKNOWLEDGED, ERR_CHILD_SESSION, ERR_NO_RUNTIME, MAX_BRIEF_FILES, NOTIFY_CUSTOM_TYPE };
@@ -1,3 +1,3 @@
1
1
  import { t as MAX_BRIEF_FILES } from "./delegation-BiOy3_7g.mjs";
2
- import { a as ERR_NO_RUNTIME, i as ERR_CHILD_SESSION, n as DelegationManager, o as NOTIFY_CUSTOM_TYPE, r as ERR_CANCEL_UNACKNOWLEDGED, t as BACKGROUND_WORK_PROVIDER } from "./delegation-Dsqf7fUM.mjs";
2
+ import { a as ERR_NO_RUNTIME, i as ERR_CHILD_SESSION, n as DelegationManager, o as NOTIFY_CUSTOM_TYPE, r as ERR_CANCEL_UNACKNOWLEDGED, t as BACKGROUND_WORK_PROVIDER } from "./delegation-5TOl_dEq.mjs";
3
3
  export { BACKGROUND_WORK_PROVIDER, DelegationManager, ERR_CANCEL_UNACKNOWLEDGED, ERR_CHILD_SESSION, ERR_NO_RUNTIME, MAX_BRIEF_FILES, NOTIFY_CUSTOM_TYPE };