@skrr-ai/cli 0.1.143 → 0.1.145

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 (102) hide show
  1. package/README.md +13 -0
  2. package/dist/commands/agenda/plan.d.ts +7 -0
  3. package/dist/commands/agenda/plan.js +17 -0
  4. package/dist/commands/agenda/trigger/create.js +4 -2
  5. package/dist/commands/agenda/trigger/list.js +7 -7
  6. package/dist/commands/agent/message/approve.d.ts +17 -0
  7. package/dist/commands/agent/message/approve.js +70 -0
  8. package/dist/commands/agent/message/decline.d.ts +17 -0
  9. package/dist/commands/agent/message/decline.js +70 -0
  10. package/dist/commands/agent/message/pending.d.ts +18 -0
  11. package/dist/commands/agent/message/pending.js +79 -0
  12. package/dist/commands/agents/delete.d.ts +45 -0
  13. package/dist/commands/agents/delete.js +139 -2
  14. package/dist/commands/agents/plan-day.d.ts +50 -7
  15. package/dist/commands/agents/plan-day.js +293 -65
  16. package/dist/commands/agents/proactive-audit.d.ts +22 -0
  17. package/dist/commands/agents/proactive-audit.js +86 -0
  18. package/dist/commands/agents/schedule-overview.d.ts +7 -0
  19. package/dist/commands/agents/schedule-overview.js +49 -5
  20. package/dist/commands/agents/schedule-trace.js +42 -21
  21. package/dist/commands/agents/spawn.d.ts +78 -1
  22. package/dist/commands/agents/spawn.js +262 -6
  23. package/dist/commands/agents/todos/list.d.ts +5 -0
  24. package/dist/commands/agents/todos/list.js +19 -5
  25. package/dist/commands/agents/triggers/create.js +1 -1
  26. package/dist/commands/agents/triggers/update.js +1 -1
  27. package/dist/commands/agents/upcoming.d.ts +1 -0
  28. package/dist/commands/agents/upcoming.js +18 -7
  29. package/dist/commands/commitments/create.js +14 -4
  30. package/dist/commands/commitments/preflight.js +14 -3
  31. package/dist/commands/commitments/update.js +1 -1
  32. package/dist/commands/initiatives/worker/deactivate.d.ts +23 -0
  33. package/dist/commands/initiatives/worker/deactivate.js +78 -0
  34. package/dist/commands/login.js +8 -2
  35. package/dist/commands/logout.d.ts +20 -0
  36. package/dist/commands/logout.js +110 -5
  37. package/dist/commands/memory/maintain.js +16 -2
  38. package/dist/commands/spaces/delete.js +6 -1
  39. package/dist/commands/spaces/workflow-templates/insert.js +4 -0
  40. package/dist/commands/spaces/workflows/archive.js +6 -1
  41. package/dist/commands/spaces/workflows/publish.js +3 -1
  42. package/dist/commands/spaces/workflows/run.d.ts +1 -0
  43. package/dist/commands/spaces/workflows/run.js +17 -1
  44. package/dist/commands/spaces/workflows/triggers/create.js +3 -1
  45. package/dist/commands/store/show.js +22 -0
  46. package/dist/commands/tasks/workflow-context.js +3 -1
  47. package/dist/commands/triggers/capabilities.js +17 -1
  48. package/dist/commands/triggers/create.d.ts +2 -0
  49. package/dist/commands/triggers/create.js +23 -7
  50. package/dist/commands/triggers/fire-detail.js +12 -3
  51. package/dist/commands/triggers/list.d.ts +1 -0
  52. package/dist/commands/triggers/list.js +13 -1
  53. package/dist/commands/triggers/preflight.js +18 -0
  54. package/dist/commands/triggers/prune.js +9 -5
  55. package/dist/commands/triggers/update.js +13 -4
  56. package/dist/generated/agent-guides.json +35 -35
  57. package/dist/lib/agent-proactive-baseline.js +7 -1
  58. package/dist/lib/agentic-stream.d.ts +7 -0
  59. package/dist/lib/agentic-stream.js +22 -0
  60. package/dist/lib/commitments.d.ts +16 -9
  61. package/dist/lib/commitments.js +78 -5
  62. package/dist/lib/compasses.js +1 -1
  63. package/dist/lib/daemon-setup.js +9 -3
  64. package/dist/lib/daemonBroker.d.ts +7 -0
  65. package/dist/lib/daemonBroker.js +5 -0
  66. package/dist/lib/daemonHandoff.d.ts +2 -0
  67. package/dist/lib/daemonHandoff.js +10 -1
  68. package/dist/lib/daemonIslandProfile.d.ts +19 -0
  69. package/dist/lib/daemonIslandProfile.js +41 -0
  70. package/dist/lib/dedicated-power.js +10 -3
  71. package/dist/lib/format.d.ts +47 -0
  72. package/dist/lib/format.js +136 -1
  73. package/dist/lib/initiatives-worker.d.ts +25 -0
  74. package/dist/lib/initiatives-worker.js +13 -0
  75. package/dist/lib/login.d.ts +7 -0
  76. package/dist/lib/login.js +5 -0
  77. package/dist/lib/planOutcome.d.ts +51 -0
  78. package/dist/lib/planOutcome.js +88 -0
  79. package/dist/lib/proactive-audit.d.ts +52 -0
  80. package/dist/lib/proactive-audit.js +67 -0
  81. package/dist/lib/proactiveApi.d.ts +71 -0
  82. package/dist/lib/proactiveApi.js +10 -1
  83. package/dist/lib/refresh.d.ts +20 -6
  84. package/dist/lib/refresh.js +27 -9
  85. package/dist/lib/roles.d.ts +1 -1
  86. package/dist/lib/schedule.d.ts +214 -10
  87. package/dist/lib/schedule.js +317 -21
  88. package/dist/lib/triggers.d.ts +139 -3
  89. package/dist/lib/triggers.js +382 -18
  90. package/dist/lib/workflow-node-control.js +8 -0
  91. package/dist/lib/workflow-run-view.js +9 -0
  92. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/index.d.ts +1 -1
  93. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/index.js +2 -0
  94. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/refresh.d.ts +22 -0
  95. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/refresh.js +15 -4
  96. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/index.d.ts +1 -1
  97. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/index.js +1 -1
  98. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/refresh.d.ts +22 -0
  99. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/refresh.js +22 -4
  100. package/dist/node_modules/@skrr-ai/data-provider/index.js +5252 -5211
  101. package/oclif.manifest.json +526 -29
  102. package/package.json +1 -1
@@ -12,7 +12,13 @@ import { BaseCommand } from '../../base-command';
12
12
  *
13
13
  * A proposal is a DRAFT — nothing is scheduled until `--approve`. Re-running the
14
14
  * bare command recovers the pending proposal rather than regenerating it (mirrors
15
- * the board, which recovers a pending plan into the review modal).
15
+ * the board, which recovers a pending plan into the review modal). With NO
16
+ * pending plan the bare command starts a real planner run, and says so before it
17
+ * does; `--regenerate` is the explicit way to replace a pending plan.
18
+ *
19
+ * Times are shown in the plan's own timezone, named. A plan is proposed in
20
+ * `--timezone`, or this machine's zone: the same default `schedule-trace` and
21
+ * `todos list` use, so one agent-day is one zone across the commands.
16
22
  */
17
23
  export default class AgentsPlanDay extends BaseCommand {
18
24
  static description: string;
@@ -41,18 +47,55 @@ export default class AgentsPlanDay extends BaseCommand {
41
47
  * --json` did when the transport handed back an unparseable body (OSK-2803).
42
48
  */
43
49
  private requireProposal;
44
- /** `{proposal}` envelope reader that survives a body-less response. */
45
- private fetchPending;
50
+ /**
51
+ * `{proposal, planRequest}` envelope reader that survives a body-less response.
52
+ *
53
+ * `planRequest` is the server's own record of whether a plan is being
54
+ * generated, failed, or went quiet. It is what lets this command answer from
55
+ * the server's side instead of guessing from a timeout.
56
+ */
57
+ private fetchPendingState;
58
+ /** Refuse an action on the draft while its replacement is being generated. */
59
+ private refuseWhileGenerating;
46
60
  private workingHoursOverride;
47
61
  /**
48
62
  * Gateway failures can interrupt a response after the planner started.
49
- * Check the durable draft before suggesting another billable request; a
63
+ * Check the server's record before suggesting another billable request; a
50
64
  * 502 can also mean the planner never started, so do not assert that it did.
51
65
  */
52
66
  private static readonly TIMEOUT_STATUSES;
53
- /** Bounded, honest recovery poll. A daemon-run plan lands in ~2-4 minutes. */
54
- private static readonly RECOVERY_ATTEMPTS;
55
- private static readonly RECOVERY_INTERVAL_MS;
67
+ private static readonly POLL_INTERVAL_MS;
68
+ /** Following a request the server named: it is known to be recorded, so ask more often. */
69
+ private static readonly FOLLOW_INTERVAL_MS;
70
+ /** Without a plan-request record (older server) the wait is the old, bounded guess. */
71
+ private static readonly LEGACY_POLL_ATTEMPTS;
72
+ /** The longest a planner may run is ~12 min; wait that plus a margin, never forever. */
73
+ private static readonly MAX_WAIT_MS;
74
+ /** A finished request's draft can lag a replica read; allow a few polls for it. */
75
+ private static readonly DRAFT_LAG_POLLS;
76
+ /**
77
+ * Wait for a plan request to settle, reading the server's record each time.
78
+ *
79
+ * `target` says which request matters:
80
+ * - `existing`: one we found running, and want the result of.
81
+ * - `ours`: the request our POST started, whose response was lost. We only
82
+ * know the id of whatever was on record BEFORE posting, so a record that is
83
+ * missing or unchanged means the server never saw our request start.
84
+ * - `accepted`: the request the server named in a 202. It is known to be
85
+ * recorded, so a read that does not show it yet predates it and is ignored.
86
+ *
87
+ * Returns instead of throwing for the three "no draft" endings so the caller
88
+ * decides what each means; a request that FAILED throws with the reason,
89
+ * because that is the one answer the person has been missing.
90
+ */
91
+ private awaitPlanRequest;
92
+ /**
93
+ * The server answered 202: it claimed the plan day and is still planning. That is
94
+ * neither a plan nor a failure, so follow the request it named until it settles.
95
+ * A request that FAILED throws with the reason (inside the wait); every other
96
+ * ending without a draft is reported here, because the person asked for a plan.
97
+ */
98
+ private followAcceptedPlan;
56
99
  /**
57
100
  * After a timed-out propose, collect the draft the server persisted anyway.
58
101
  * Returns null when the failure was not a timeout, or when nothing landed —
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const core_1 = require("@oclif/core");
4
4
  const base_command_1 = require("../../base-command");
5
+ const format_1 = require("../../lib/format");
5
6
  const schedule_1 = require("../../lib/schedule");
6
7
  /**
7
8
  * `skrr agents plan-day <agent-id>` — Smart Schedule ("Plan my day").
@@ -16,7 +17,13 @@ const schedule_1 = require("../../lib/schedule");
16
17
  *
17
18
  * A proposal is a DRAFT — nothing is scheduled until `--approve`. Re-running the
18
19
  * bare command recovers the pending proposal rather than regenerating it (mirrors
19
- * the board, which recovers a pending plan into the review modal).
20
+ * the board, which recovers a pending plan into the review modal). With NO
21
+ * pending plan the bare command starts a real planner run, and says so before it
22
+ * does; `--regenerate` is the explicit way to replace a pending plan.
23
+ *
24
+ * Times are shown in the plan's own timezone, named. A plan is proposed in
25
+ * `--timezone`, or this machine's zone: the same default `schedule-trace` and
26
+ * `todos list` use, so one agent-day is one zone across the commands.
20
27
  */
21
28
  class AgentsPlanDay extends base_command_1.BaseCommand {
22
29
  static description = "Smart Schedule an agent's day: propose a plan, then approve or dismiss it";
@@ -44,7 +51,9 @@ class AgentsPlanDay extends base_command_1.BaseCommand {
44
51
  }),
45
52
  'hours-start': core_1.Flags.string({ description: 'Working-hours start (HH:MM) for the proposal' }),
46
53
  'hours-end': core_1.Flags.string({ description: 'Working-hours end (HH:MM) for the proposal' }),
47
- timezone: core_1.Flags.string({ description: 'IANA timezone for the working-hours window' }),
54
+ timezone: core_1.Flags.string({
55
+ description: "IANA timezone for the plan day and its working hours (defaults to this machine's timezone, as in schedule-trace and todos list)",
56
+ }),
48
57
  'approve-next-run': core_1.Flags.boolean({
49
58
  description: 'With --approve, schedule the suggested next planning run',
50
59
  dependsOn: ['approve'],
@@ -57,13 +66,8 @@ class AgentsPlanDay extends base_command_1.BaseCommand {
57
66
  this.requireAuth();
58
67
  const { args, flags } = await this.parse(AgentsPlanDay);
59
68
  const agentId = args.id;
60
- if (!flags.dismiss && !flags.approve && flags.timezone) {
61
- try {
62
- new Intl.DateTimeFormat('en', { timeZone: flags.timezone });
63
- }
64
- catch {
65
- this.error(`Invalid IANA timezone: ${flags.timezone}`, { exit: 1 });
66
- }
69
+ if (!flags.dismiss && !flags.approve && flags.timezone && !(0, schedule_1.isValidTimeZone)(flags.timezone)) {
70
+ this.error(`Invalid IANA timezone: ${flags.timezone}`, { exit: 1 });
67
71
  }
68
72
  try {
69
73
  if (flags.dismiss) {
@@ -101,10 +105,20 @@ class AgentsPlanDay extends base_command_1.BaseCommand {
101
105
  details: { agentId, operation },
102
106
  });
103
107
  }
104
- /** `{proposal}` envelope reader that survives a body-less response. */
105
- async fetchPending(agentId) {
108
+ /**
109
+ * `{proposal, planRequest}` envelope reader that survives a body-less response.
110
+ *
111
+ * `planRequest` is the server's own record of whether a plan is being
112
+ * generated, failed, or went quiet. It is what lets this command answer from
113
+ * the server's side instead of guessing from a timeout.
114
+ */
115
+ async fetchPendingState(agentId, { lenient = false } = {}) {
106
116
  const pending = (await schedule_1.scheduleApi.pendingProposal(agentId));
107
117
  if (pending == null || typeof pending !== 'object') {
118
+ // A caller that only wants context (and will carry on without it) must not
119
+ // have a broken body turned into a printed error envelope.
120
+ if (lenient)
121
+ return { proposal: null, planRequest: null, recorded: false };
108
122
  this.failWithCliError({
109
123
  message: `Could not read the pending Smart Schedule plan for agent ${agentId} ` +
110
124
  `(${(0, schedule_1.describeNonProposal)(pending)}).`,
@@ -114,13 +128,28 @@ class AgentsPlanDay extends base_command_1.BaseCommand {
114
128
  details: { agentId },
115
129
  });
116
130
  }
131
+ const recorded = 'planRequest' in pending;
132
+ const planRequest = pending.planRequest ?? null;
117
133
  const proposal = pending.proposal;
118
134
  // An explicit `null` is a real answer — "no pending plan" — and every
119
135
  // caller here already handles it. Anything else that is not a proposal is
120
136
  // a broken response, not an empty one.
121
137
  if (proposal == null)
122
- return null;
123
- return this.requireProposal(proposal, agentId, 'pending');
138
+ return { proposal: null, planRequest, recorded };
139
+ return { proposal: this.requireProposal(proposal, agentId, 'pending'), planRequest, recorded };
140
+ }
141
+ /** Refuse an action on the draft while its replacement is being generated. */
142
+ refuseWhileGenerating(agentId, state) {
143
+ if (!state.planRequest?.holds)
144
+ return;
145
+ this.failWithCliError({
146
+ message: `${(0, schedule_1.describePlanRequest)(state.planRequest)} ` +
147
+ `Run \`${this.config.bin} agents plan-day ${agentId}\` to wait for it.`,
148
+ code: 'SMART_SCHEDULE_PLAN_IN_PROGRESS',
149
+ exit: 1,
150
+ retryable: true,
151
+ details: { agentId, planRequest: state.planRequest },
152
+ });
124
153
  }
125
154
  workingHoursOverride(flags) {
126
155
  if (!flags['hours-start'] || !flags['hours-end'])
@@ -133,65 +162,231 @@ class AgentsPlanDay extends base_command_1.BaseCommand {
133
162
  }
134
163
  /**
135
164
  * Gateway failures can interrupt a response after the planner started.
136
- * Check the durable draft before suggesting another billable request; a
165
+ * Check the server's record before suggesting another billable request; a
137
166
  * 502 can also mean the planner never started, so do not assert that it did.
138
167
  */
139
168
  static TIMEOUT_STATUSES = new Set([408, 502, 504, 524]);
140
- /** Bounded, honest recovery poll. A daemon-run plan lands in ~2-4 minutes. */
141
- static RECOVERY_ATTEMPTS = 12;
142
- static RECOVERY_INTERVAL_MS = 15_000;
169
+ static POLL_INTERVAL_MS = 15_000;
170
+ /** Following a request the server named: it is known to be recorded, so ask more often. */
171
+ static FOLLOW_INTERVAL_MS = 5_000;
172
+ /** Without a plan-request record (older server) the wait is the old, bounded guess. */
173
+ static LEGACY_POLL_ATTEMPTS = 12;
174
+ /** The longest a planner may run is ~12 min; wait that plus a margin, never forever. */
175
+ static MAX_WAIT_MS = 15 * 60_000;
176
+ /** A finished request's draft can lag a replica read; allow a few polls for it. */
177
+ static DRAFT_LAG_POLLS = 4;
178
+ /**
179
+ * Wait for a plan request to settle, reading the server's record each time.
180
+ *
181
+ * `target` says which request matters:
182
+ * - `existing`: one we found running, and want the result of.
183
+ * - `ours`: the request our POST started, whose response was lost. We only
184
+ * know the id of whatever was on record BEFORE posting, so a record that is
185
+ * missing or unchanged means the server never saw our request start.
186
+ * - `accepted`: the request the server named in a 202. It is known to be
187
+ * recorded, so a read that does not show it yet predates it and is ignored.
188
+ *
189
+ * Returns instead of throwing for the three "no draft" endings so the caller
190
+ * decides what each means; a request that FAILED throws with the reason,
191
+ * because that is the one answer the person has been missing.
192
+ */
193
+ async awaitPlanRequest(agentId, target, json, intervalMs = AgentsPlanDay.POLL_INTERVAL_MS) {
194
+ const startedAt = Date.now();
195
+ let legacyPolls = 0;
196
+ let lagPolls = 0;
197
+ while (Date.now() - startedAt < AgentsPlanDay.MAX_WAIT_MS) {
198
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
199
+ let state;
200
+ try {
201
+ state = await this.fetchPendingState(agentId);
202
+ }
203
+ catch {
204
+ // A read failing mid-wait is not itself the answer; keep waiting.
205
+ continue;
206
+ }
207
+ const request = state.planRequest;
208
+ if (!state.recorded) {
209
+ // Older server: no record to read, so fall back to "a draft appeared".
210
+ legacyPolls += 1;
211
+ if (state.proposal)
212
+ return { outcome: 'proposal', proposal: state.proposal };
213
+ if (legacyPolls >= AgentsPlanDay.LEGACY_POLL_ATTEMPTS)
214
+ return { outcome: 'gave_up' };
215
+ continue;
216
+ }
217
+ if (request?.holds)
218
+ continue;
219
+ if (target.kind === 'accepted' &&
220
+ (0, schedule_1.acceptedPlanVerdict)(request, target.accepted) === 'waiting') {
221
+ continue;
222
+ }
223
+ if (target.kind === 'ours' && (!request || request.requestId === target.baselineRequestId)) {
224
+ return { outcome: 'unrecorded' };
225
+ }
226
+ if (!request)
227
+ return { outcome: 'gave_up' };
228
+ if (request.state === 'failed') {
229
+ this.failWithCliError({
230
+ message: (0, schedule_1.describePlanRequest)(request) ?? 'The planning request failed.',
231
+ code: 'SMART_SCHEDULE_PLAN_FAILED',
232
+ exit: 1,
233
+ retryable: true,
234
+ details: { agentId, planRequest: request },
235
+ });
236
+ }
237
+ if (request.state === 'unknown')
238
+ return { outcome: 'unknown' };
239
+ // succeeded
240
+ if (state.proposal) {
241
+ if (!json) {
242
+ this.log(`The plan was ready ${Math.round((Date.now() - startedAt) / 1000)}s after waiting began.`);
243
+ }
244
+ return { outcome: 'proposal', proposal: state.proposal };
245
+ }
246
+ lagPolls += 1;
247
+ if (lagPolls >= AgentsPlanDay.DRAFT_LAG_POLLS)
248
+ return { outcome: 'gave_up' };
249
+ }
250
+ return { outcome: 'gave_up' };
251
+ }
252
+ /**
253
+ * The server answered 202: it claimed the plan day and is still planning. That is
254
+ * neither a plan nor a failure, so follow the request it named until it settles.
255
+ * A request that FAILED throws with the reason (inside the wait); every other
256
+ * ending without a draft is reported here, because the person asked for a plan.
257
+ */
258
+ async followAcceptedPlan(agentId, accepted, json) {
259
+ const day = accepted.planRequest?.planDate;
260
+ // stderr, so `--json` stdout stays a single parseable document.
261
+ this.warn(`The plan${day ? ` for ${day}` : ''} is being generated on the server ` +
262
+ '(it takes longer than one request may wait). Waiting for it to finish.');
263
+ const waited = await this.awaitPlanRequest(agentId, { kind: 'accepted', accepted: accepted.planRequest }, json, AgentsPlanDay.FOLLOW_INTERVAL_MS);
264
+ if (waited.outcome === 'proposal')
265
+ return waited.proposal;
266
+ const interrupted = waited.outcome === 'unknown';
267
+ return this.failWithCliError({
268
+ message: interrupted
269
+ ? `The planning request for ${agentId} stopped reporting and may have been interrupted. ` +
270
+ `Run \`${this.config.bin} agents plan-day ${agentId}\` to check for a draft or plan again; ` +
271
+ 'if it was still running, a second draft may appear.'
272
+ : `The plan for ${agentId} was not ready within the wait. ` +
273
+ `Check \`${this.config.bin} agents plan-day ${agentId}\` again before planning another.`,
274
+ code: interrupted ? 'SMART_SCHEDULE_PLAN_INTERRUPTED' : 'SMART_SCHEDULE_PLAN_NOT_READY',
275
+ exit: 1,
276
+ retryable: true,
277
+ details: { agentId, planRequest: accepted.planRequest },
278
+ });
279
+ }
143
280
  /**
144
281
  * After a timed-out propose, collect the draft the server persisted anyway.
145
282
  * Returns null when the failure was not a timeout, or when nothing landed —
146
283
  * in both cases the caller rethrows the original error rather than inventing
147
284
  * a friendlier one.
148
285
  */
149
- async recoverProposalAfterTimeout(agentId, err, json) {
286
+ async recoverProposalAfterTimeout(agentId, err, json, baselineRequestId) {
150
287
  const status = err?.status;
151
288
  if (typeof status !== 'number' || !AgentsPlanDay.TIMEOUT_STATUSES.has(status)) {
152
289
  return null;
153
290
  }
154
291
  // stderr, so `--json` stdout stays a single parseable document.
155
292
  this.warn(`The plan request for ${agentId} was interrupted (HTTP ${status}). ` +
156
- 'The run may still be finishing; checking for its saved draft before starting another.');
157
- for (let attempt = 1; attempt <= AgentsPlanDay.RECOVERY_ATTEMPTS; attempt += 1) {
158
- await new Promise((resolve) => setTimeout(resolve, AgentsPlanDay.RECOVERY_INTERVAL_MS));
159
- let pending = null;
160
- try {
161
- pending = (await schedule_1.scheduleApi.pendingProposal(agentId));
162
- }
163
- catch {
164
- // A read failing mid-recovery is not itself the answer — keep waiting
165
- // until the attempt budget is spent, then surface the ORIGINAL error.
166
- continue;
167
- }
168
- const candidate = pending?.proposal;
169
- if (candidate != null && (0, schedule_1.isSmartScheduleProposal)(candidate)) {
170
- if (!json) {
171
- this.log(`Recovered the plan after ${attempt * (AgentsPlanDay.RECOVERY_INTERVAL_MS / 1000)}s.`);
172
- }
173
- return candidate;
174
- }
293
+ "The run may still be finishing; checking the server's record of it before starting another.");
294
+ const waited = await this.awaitPlanRequest(agentId, { kind: 'ours', baselineRequestId }, json);
295
+ switch (waited.outcome) {
296
+ case 'proposal':
297
+ return waited.proposal;
298
+ case 'unrecorded':
299
+ this.warn(`The server has no record of this request starting, so nothing appears to be running for ${agentId}. ` +
300
+ 'Run the command again.');
301
+ return null;
302
+ case 'unknown':
303
+ this.warn('The request stopped reporting and may have been interrupted. ' +
304
+ 'Run the command again to plan; if it was still running, a second draft may appear.');
305
+ return null;
306
+ default:
307
+ this.warn(`No plan for ${agentId} became readable. ` +
308
+ `Check \`${this.config.bin} agents plan-day ${agentId}\` again before regenerating — ` +
309
+ 'a second propose starts a second billable run.');
310
+ return null;
175
311
  }
176
- this.warn(`No plan for ${agentId} became readable within ` +
177
- `${(AgentsPlanDay.RECOVERY_ATTEMPTS * AgentsPlanDay.RECOVERY_INTERVAL_MS) / 1000}s. ` +
178
- 'Check `skrr agents plan-day ' +
179
- agentId +
180
- '` again before regenerating — a second propose starts a second billable run.');
181
- return null;
182
312
  }
183
313
  async runProposeOrShow(agentId, flags) {
184
314
  let proposal = null;
185
- // Recover a pending draft unless the caller explicitly wants a fresh one.
186
- if (flags.regenerate === undefined) {
187
- proposal = await this.fetchPending(agentId);
315
+ // The zone the plan is proposed in. Sent explicitly: left to the server it
316
+ // falls back to the account's last-seen browser zone, which is not this
317
+ // machine's and shifted between runs (America/Los_Angeles, then
318
+ // America/Vancouver for the same agent and minute, OSK-22397).
319
+ const timezone = (0, schedule_1.resolveDayTimeZone)(flags.timezone) ?? 'UTC';
320
+ // Read the server's view first, whether or not a draft is wanted: whether a
321
+ // plan is already being generated decides everything that follows, and it
322
+ // is the baseline that tells a lost POST apart from one that never started.
323
+ let before = null;
324
+ try {
325
+ before = await this.fetchPendingState(agentId, { lenient: flags.regenerate !== undefined });
326
+ }
327
+ catch (readErr) {
328
+ // A fresh plan was never gated on this read; keep it that way.
329
+ if (flags.regenerate === undefined)
330
+ throw readErr;
331
+ }
332
+ if (before?.planRequest?.holds) {
333
+ if (flags.regenerate !== undefined)
334
+ this.refuseWhileGenerating(agentId, before);
335
+ // Someone (the web, another terminal, the agent) is already generating
336
+ // this plan. A second request would only be refused, and the answer the
337
+ // person wants is that plan.
338
+ this.warn((0, schedule_1.describePlanRequest)(before.planRequest) ?? 'A plan is being generated.');
339
+ this.warn('Waiting for it to finish.');
340
+ const waited = await this.awaitPlanRequest(agentId, { kind: 'existing' }, flags.json);
341
+ if (waited.outcome === 'proposal') {
342
+ proposal = waited.proposal;
343
+ }
344
+ else if (waited.outcome === 'unknown') {
345
+ this.warn('That request stopped reporting and may have been interrupted, so it no longer blocks planning.');
346
+ before = { ...before, planRequest: null };
347
+ proposal = before.proposal;
348
+ }
349
+ else {
350
+ this.failWithCliError({
351
+ message: `The plan for ${agentId} did not finish within the wait. ` +
352
+ `Check \`${this.config.bin} agents plan-day ${agentId}\` again.`,
353
+ code: 'SMART_SCHEDULE_PLAN_NOT_READY',
354
+ exit: 1,
355
+ retryable: true,
356
+ details: { agentId },
357
+ });
358
+ }
359
+ }
360
+ else if (flags.regenerate === undefined) {
361
+ // Recover a pending draft unless the caller explicitly wants a fresh one.
362
+ proposal = before?.proposal ?? null;
188
363
  }
364
+ // A planning attempt that FAILED is history the person should see, but not a
365
+ // reason to refuse: they asked to plan, and the next attempt may work.
366
+ let priorAttempt = null;
367
+ if (before?.planRequest?.state === 'failed' || before?.planRequest?.state === 'unknown') {
368
+ priorAttempt = before.planRequest;
369
+ this.warn((0, schedule_1.describePlanRequest)(priorAttempt) ?? '');
370
+ }
371
+ const showingPending = proposal !== null;
189
372
  if (!proposal) {
373
+ // Planning is a real, billable agent run (~20s to a few minutes). Say so
374
+ // BEFORE starting it: a bare `plan-day` after an approval used to look
375
+ // like a status check and silently produced a second draft (OSK-22403).
376
+ if (!flags.json) {
377
+ this.log(flags.regenerate === undefined
378
+ ? `No pending plan for ${agentId}; asking the planner for a new draft. This runs the agent and can take a minute or more.`
379
+ : `Asking the planner for a fresh plan for ${agentId}, replacing any pending one. This runs the agent and can take a minute or more.`);
380
+ if (flags.regenerate === undefined) {
381
+ this.log(`To look at what is already scheduled without planning: ${this.config.bin} agents todos list ${agentId}, ${this.config.bin} agents schedule-trace ${agentId}`);
382
+ }
383
+ this.log('');
384
+ }
190
385
  let generated;
191
386
  try {
192
387
  generated = await schedule_1.scheduleApi.proposeSmartSchedule({
193
388
  agentId,
194
- ...(flags.timezone ? { timezone: flags.timezone } : {}),
389
+ timezone,
195
390
  ...(this.workingHoursOverride(flags)
196
391
  ? { workingHoursOverride: this.workingHoursOverride(flags) }
197
392
  : {}),
@@ -210,30 +405,47 @@ class AgentsPlanDay extends base_command_1.BaseCommand {
210
405
  // Recovering the durable draft is also why this must never re-POST
211
406
  // propose: a blind retry starts a SECOND run the user pays for while
212
407
  // the first one is still finishing.
213
- const recovered = await this.recoverProposalAfterTimeout(agentId, err, flags.json);
408
+ const recovered = await this.recoverProposalAfterTimeout(agentId, err, flags.json, before?.planRequest?.requestId ?? null);
214
409
  if (!recovered)
215
410
  throw err;
216
411
  proposal = recovered;
217
412
  }
413
+ if (!proposal && (0, schedule_1.isPlanAccepted)(generated)) {
414
+ proposal = await this.followAcceptedPlan(agentId, generated, flags.json);
415
+ }
218
416
  if (!proposal) {
219
417
  proposal = this.requireProposal(generated, agentId, 'propose');
220
418
  }
221
419
  }
222
420
  if (flags.json) {
223
- this.log(JSON.stringify(proposal, null, 2));
421
+ // Additive: when the draft shown is an older one, the attempt after it that
422
+ // did not produce a newer. A freshly generated draft supersedes that history.
423
+ const showsOlderDraft = priorAttempt !== null && proposal === before?.proposal;
424
+ this.log(JSON.stringify(showsOlderDraft ? { ...proposal, planRequest: priorAttempt } : proposal, null, 2));
224
425
  return;
225
426
  }
427
+ if (showingPending) {
428
+ const zone = proposal.timezone || timezone;
429
+ const meta = [
430
+ proposal.version ? `v${proposal.version}` : null,
431
+ proposal.generatedAt ? `generated ${(0, format_1.zonedTime)(proposal.generatedAt, zone)}` : null,
432
+ ]
433
+ .filter(Boolean)
434
+ .join(', ');
435
+ this.log(`Showing the pending plan${meta ? ` (${meta})` : ''}; pass --regenerate to replace it with a fresh one.`);
436
+ this.log('');
437
+ }
226
438
  (0, schedule_1.renderProposal)(proposal, (line) => this.log(line));
227
439
  this.log('');
228
- this.log('This is a draft — nothing is scheduled yet.');
229
- this.log(` Approve: ${this.config.bin} agents plan-day ${agentId} --approve`);
230
- if (proposal.nextRunSuggestion) {
231
- this.log(` Include next run: ${this.config.bin} agents plan-day ${agentId} --approve --approve-next-run`);
232
- }
233
- this.log(` Discard: ${this.config.bin} agents plan-day ${agentId} --dismiss`);
440
+ for (const line of (0, schedule_1.proposalNextSteps)(proposal, this.config.bin, agentId))
441
+ this.log(line);
234
442
  }
235
443
  async runApprove(agentId, flags) {
236
- const proposal = await this.fetchPending(agentId);
444
+ const state = await this.fetchPendingState(agentId);
445
+ // The server refuses this too; saying so here names the request and the way
446
+ // to wait for it instead of surfacing a bare 409.
447
+ this.refuseWhileGenerating(agentId, state);
448
+ const proposal = state.proposal;
237
449
  if (!proposal) {
238
450
  this.error(`No pending plan for agent ${agentId}. Run \`${this.config.bin} agents plan-day ${agentId}\` first.`, { exit: 4 });
239
451
  }
@@ -242,9 +454,10 @@ class AgentsPlanDay extends base_command_1.BaseCommand {
242
454
  this.error('The pending proposal has no suggested next run to approve.', { exit: 1 });
243
455
  }
244
456
  if (todos.length === 0 && !flags['approve-next-run']) {
457
+ const base = `${this.config.bin} agents plan-day ${agentId}`;
245
458
  const next = proposal.nextRunSuggestion
246
- ? ` Use --approve --approve-next-run to schedule its suggested next run, or --dismiss to discard it.`
247
- : ' Use --dismiss to discard it.';
459
+ ? ` To accept it and schedule its suggested next run, run \`${base} --approve --approve-next-run\` (two flags). To discard it, run \`${base} --dismiss\`.`
460
+ : ` There is nothing to approve; discard it with \`${base} --dismiss\`.`;
248
461
  this.error(`The pending proposal has no schedulable to-dos.${next}`, { exit: 1 });
249
462
  }
250
463
  const result = await schedule_1.scheduleApi.approveSmartSchedule({
@@ -273,12 +486,20 @@ class AgentsPlanDay extends base_command_1.BaseCommand {
273
486
  this.log(JSON.stringify(result, null, 2));
274
487
  return;
275
488
  }
489
+ const zone = proposal.timezone || flags.timezone || 'UTC';
276
490
  this.log(`Approved plan ${proposal.proposalId}: created ${result.created.length} to-do(s).`);
277
- (0, schedule_1.renderCapacityWarning)(result.capacity, (line) => this.log(line));
278
- if (flags['approve-next-run']) {
279
- this.log(result.scheduledNextRun?.created
280
- ? `Next planning run scheduled${result.scheduledNextRun.triggerId ? ` (${result.scheduledNextRun.triggerId})` : ''}.`
281
- : `Next planning run was not created${result.scheduledNextRun?.message || result.scheduledNextRun?.skippedReason ? `: ${result.scheduledNextRun.message || result.scheduledNextRun.skippedReason}` : '.'}`);
491
+ if (result.replaced?.cancelled?.length) {
492
+ this.log(`Cancelled ${result.replaced.cancelled.length} earlier pending block(s) the plan replaced: ` +
493
+ result.replaced.cancelled.join(', '));
494
+ }
495
+ (0, schedule_1.renderCapacityWarning)(result.capacity, (line) => this.log(line), agentId, 'approved');
496
+ for (const line of (0, schedule_1.approvalEffectLines)(result, {
497
+ approvedNextRun: Boolean(flags['approve-next-run']),
498
+ timeZone: zone,
499
+ bin: this.config.bin,
500
+ agentId,
501
+ })) {
502
+ this.log(line);
282
503
  }
283
504
  if (result.failed.length > 0) {
284
505
  this.log(`${result.failed.length} failed:`);
@@ -286,10 +507,15 @@ class AgentsPlanDay extends base_command_1.BaseCommand {
286
507
  this.log(` - ${f.tempId ?? '?'}: ${f.code} ${f.message}`);
287
508
  }
288
509
  }
289
- this.log(`See them with: ${this.config.bin} agents todos list ${agentId}`);
510
+ // Name the day and zone the plan covers: a bare `todos list` shows today in
511
+ // the machine's zone, which is not the plan's day when they differ.
512
+ const dayFlags = `${proposal.planDate ? ` --date ${proposal.planDate}` : ''} --timezone ${zone}`;
513
+ this.log(`See them with: ${this.config.bin} agents todos list ${agentId}${dayFlags}`);
290
514
  }
291
515
  async runDismiss(agentId, json) {
292
- const proposal = await this.fetchPending(agentId);
516
+ const state = await this.fetchPendingState(agentId);
517
+ this.refuseWhileGenerating(agentId, state);
518
+ const proposal = state.proposal;
293
519
  if (!proposal) {
294
520
  this.log(`No pending plan for agent ${agentId}.`);
295
521
  return;
@@ -300,6 +526,8 @@ class AgentsPlanDay extends base_command_1.BaseCommand {
300
526
  return;
301
527
  }
302
528
  this.log(`Dismissed plan ${proposal.proposalId}.`);
529
+ for (const line of (0, schedule_1.dismissEffectLines)(result))
530
+ this.log(line);
303
531
  }
304
532
  }
305
533
  exports.default = AgentsPlanDay;
@@ -0,0 +1,22 @@
1
+ import { BaseCommand } from '../../base-command';
2
+ /**
3
+ * `skrr agents proactive-audit <agent-id>` — who changed this agent's proactivity boundary, when
4
+ * and why, across Compass, the worker (initiatives), Smart Schedule and the goal planner, plus the
5
+ * switches its task/goal watcher runs with and whether each is a setting or the platform default.
6
+ *
7
+ * `GET /api/todos/proactive-audit` had no CLI path; the only way to read it was devtools, and
8
+ * minting a token to curl it needs an authenticator code (OSK-22418).
9
+ */
10
+ export default class AgentsProactiveAudit extends BaseCommand {
11
+ static description: string;
12
+ static examples: string[];
13
+ static args: {
14
+ agent: import("@oclif/core/interfaces").Arg<string, Record<string, unknown>>;
15
+ };
16
+ static flags: {
17
+ json: import("@oclif/core/interfaces").BooleanFlag<boolean>;
18
+ domain: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
19
+ limit: import("@oclif/core/interfaces").OptionFlag<number | undefined, import("@oclif/core/interfaces").CustomOptions>;
20
+ };
21
+ run(): Promise<void>;
22
+ }