dvm-planner 0.1.0__tar.gz

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.
@@ -0,0 +1,30 @@
1
+ name: CI
2
+
3
+ on:
4
+ pull_request:
5
+ push:
6
+ branches-ignore:
7
+ - main
8
+
9
+ jobs:
10
+ build:
11
+ runs-on: ${{ matrix.os }}
12
+ strategy:
13
+ fail-fast: false
14
+ matrix:
15
+ os: [ubuntu-latest, windows-latest]
16
+ python-version: ["3.10", "3.11", "3.12", "3.13"]
17
+ steps:
18
+ - uses: actions/checkout@v4
19
+ with:
20
+ fetch-depth: 0
21
+
22
+ - uses: astral-sh/setup-uv@v5
23
+ with:
24
+ python-version: ${{ matrix.python-version }}
25
+
26
+ - name: Build
27
+ run: uv build
28
+
29
+ - name: Smoke test
30
+ run: uv run --with . dvm-planner --help
@@ -0,0 +1,72 @@
1
+ # One-time PyPI setup: at https://pypi.org/manage/account/publishing/ add a trusted
2
+ # publisher for project "dvm-planner" with owner/repo = <github-owner>/<repo>,
3
+ # workflow = release.yml, environment = pypi (create the "pypi" environment in repo settings).
4
+ name: Release
5
+
6
+ on:
7
+ push:
8
+ branches:
9
+ - main
10
+
11
+ jobs:
12
+ tag:
13
+ runs-on: ubuntu-latest
14
+ permissions:
15
+ contents: write
16
+ outputs:
17
+ version: ${{ steps.bump.outputs.version }}
18
+ steps:
19
+ - uses: actions/checkout@v4
20
+ with:
21
+ fetch-depth: 0
22
+
23
+ - name: Compute and push next tag
24
+ id: bump
25
+ run: |
26
+ git fetch --tags --force
27
+ if [ -n "$(git tag --points-at HEAD --list 'v*')" ]; then
28
+ echo "HEAD already tagged; skipping"
29
+ echo "version=" >> "$GITHUB_OUTPUT"
30
+ exit 0
31
+ fi
32
+ latest=$(git tag --list 'v*' --sort=-v:refname | head -n 1)
33
+ if [ -z "$latest" ]; then
34
+ next="v0.1.0"
35
+ else
36
+ IFS=. read -r major minor patch <<< "${latest#v}"
37
+ next="v${major}.${minor}.$((patch + 1))"
38
+ fi
39
+ git config user.name "github-actions[bot]"
40
+ git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
41
+ git tag -a "$next" -m "Release $next"
42
+ git push origin "refs/tags/$next"
43
+ echo "version=$next" >> "$GITHUB_OUTPUT"
44
+
45
+ publish:
46
+ needs: tag
47
+ if: needs.tag.outputs.version != ''
48
+ runs-on: ubuntu-latest
49
+ environment: pypi
50
+ permissions:
51
+ contents: write
52
+ id-token: write
53
+ steps:
54
+ - uses: actions/checkout@v4
55
+ with:
56
+ fetch-depth: 0
57
+ ref: refs/tags/${{ needs.tag.outputs.version }}
58
+
59
+ - uses: astral-sh/setup-uv@v5
60
+
61
+ - name: Build
62
+ run: uv build
63
+
64
+ - name: Publish to PyPI
65
+ uses: pypa/gh-action-pypi-publish@release/v1
66
+
67
+ - name: Create GitHub Release
68
+ env:
69
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
70
+ run: |
71
+ gh release create "${{ needs.tag.outputs.version }}" dist/* \
72
+ --title "${{ needs.tag.outputs.version }}" --generate-notes
@@ -0,0 +1,5 @@
1
+ __pycache__/
2
+ dist/
3
+ *.egg-info/
4
+ .venv/
5
+ uv.lock
@@ -0,0 +1,7 @@
1
+ # Contributor / agent instructions
2
+
3
+ - On every major change (new or changed command/option, new endpoint or data source, packaging/release
4
+ change), update in the same commit: `README.md`, `docs/planner-cdp.md`, and
5
+ `src/dvm_planner/skills/dvm-planner/SKILL.md`.
6
+ - Commit messages must not name Copilot or Claude as author/co-author (no `Co-authored-by` trailers for them).
7
+ - Releases are automatic on push to `main` (see `.github/workflows/release.yml`); do not tag manually.
@@ -0,0 +1,77 @@
1
+ Metadata-Version: 2.5
2
+ Name: dvm-planner
3
+ Version: 0.1.0
4
+ Summary: Extract Microsoft Planner plans and tasks as JSON via an Edge browser (CDP)
5
+ Requires-Python: >=3.10
6
+ Requires-Dist: httpx>=0.27
7
+ Requires-Dist: websockets>=12
8
+ Description-Content-Type: text/markdown
9
+
10
+ # dvm-planner
11
+
12
+ `dvm-planner` extracts **Microsoft Planner** data (plans, buckets, tasks, assignees, due dates,
13
+ checklists) as JSON. It launches Microsoft Edge with Chrome DevTools Protocol (CDP) enabled, reuses your
14
+ signed-in Planner session to obtain the token the Planner web UI itself uses, and queries Planner's
15
+ `taskapi` directly. No app registration or admin consent is needed - only a browser signed in to Planner.
16
+
17
+ It also ships an **agent skill** so GitHub Copilot CLI and Claude Code can answer questions like
18
+ "which tasks are assigned to me?" or "list my plans" by running the tool for you.
19
+
20
+ ## Requirements
21
+ - Microsoft Edge
22
+ - [uv](https://docs.astral.sh/uv/) (for `uvx`), Python 3.10+
23
+
24
+ ## Usage
25
+ ```
26
+ uvx dvm-planner launch # start Edge (CDP port 19222, profile ~/.dvm-planner/edge-profile)
27
+ uvx dvm-planner plans # list plans (recent + favorites)
28
+ uvx dvm-planner mytasks [--summary] # tasks assigned to me, grouped by plan
29
+ uvx dvm-planner usertasks "Giampaolo" --with-due # tasks assigned to someone else (name or e-mail)
30
+ uvx dvm-planner tasks <planId|URL> # buckets + tasks of one plan
31
+ uvx dvm-planner tasks --all -o all.json # every listed plan
32
+ uvx dvm-planner update-task "North Star Layers" --due 2026-12-31 --comment "Updated" # id or title fragment
33
+ ```
34
+ uvx dvm-planner remind --list [--json] # my open tasks with due dates, numbered
35
+ uvx dvm-planner remind --select 1,3-5 # Outlook event "Planner: <task>" on the due date (09:00, 30 min, reminder 1 day before)
36
+ uvx dvm-planner remind --all --dry-run # or --task "title"; non-interactive when not on a TTY
37
+ uvx dvm-planner remind --sync # after due dates change: move matching events to the new date
38
+ ```
39
+ `remind` options: `--at HH:MM`, `--duration MIN`, `--reminder-minutes N`, `--on DATE`, `--show-as`,
40
+ `--include-past`, `--include-done`, `--include-no-due`. Past dates and existing events are skipped.
41
+ With no selector on a terminal it prompts for numbers.
42
+
43
+ `update-task` options: `--due YYYY-MM-DD|none`, `--notes HTML`, `--add-checklist TEXT` (repeatable),
44
+ `--comment TEXT`, `--patch JSON` (raw body, for fields captured from the UI - see docs).
45
+ Options: `--port`, `--profile`, `--edge-path`, `-o/--output`. On first run sign in to Planner in the
46
+ Edge window that opens (SSO usually works automatically); the profile is reused afterwards.
47
+
48
+ Notes: `plans` covers recent/favorite plans only; due dates are in `dueDateTime.date` (`dueUtcDateTime` is legacy/null);
49
+ tokens last about an hour and are recaptured on each run.
50
+ How it works: [docs/planner-cdp.md](docs/planner-cdp.md).
51
+
52
+ ## Use with GitHub Copilot CLI
53
+ ```
54
+ uvx dvm-planner --update-skills copilot # installs to ~/.copilot/skills/dvm-planner
55
+ ```
56
+ Restart/reload Copilot CLI, then ask e.g. *"List the tasks assigned to me in Planner"*; the
57
+ `dvm-planner` skill is picked up automatically.
58
+
59
+ ## Use with Claude Code
60
+ ```
61
+ uvx dvm-planner --update-skills claude # installs to ~/.claude/skills/dvm-planner
62
+ ```
63
+ Start a new Claude Code session and ask the same kind of question.
64
+
65
+ `uvx dvm-planner --update-skills` (no value) installs for both. Re-run it after upgrading
66
+ (`uvx dvm-planner@latest --update-skills`) to refresh the skill.
67
+
68
+ ## Development & releases
69
+ Skill source: `src/dvm_planner/skills/dvm-planner/SKILL.md` (bundled in the wheel).
70
+ Every push to `main` tags the next `vX.Y.Z` and publishes to PyPI via Trusted Publishing
71
+ (one-time setup: PyPI trusted publisher for this repo, workflow `release.yml`, environment `pypi`).
72
+ The version is derived from git tags (hatch-vcs).
73
+
74
+ ### Keeping docs current (required)
75
+ On every major change (new/changed command or option, new data source/endpoint, packaging or release
76
+ change) update **in the same commit**: this README, `docs/planner-cdp.md`, and the skill
77
+ `src/dvm_planner/skills/dvm-planner/SKILL.md`. These rules are also in `AGENTS.md`.
@@ -0,0 +1,68 @@
1
+ # dvm-planner
2
+
3
+ `dvm-planner` extracts **Microsoft Planner** data (plans, buckets, tasks, assignees, due dates,
4
+ checklists) as JSON. It launches Microsoft Edge with Chrome DevTools Protocol (CDP) enabled, reuses your
5
+ signed-in Planner session to obtain the token the Planner web UI itself uses, and queries Planner's
6
+ `taskapi` directly. No app registration or admin consent is needed - only a browser signed in to Planner.
7
+
8
+ It also ships an **agent skill** so GitHub Copilot CLI and Claude Code can answer questions like
9
+ "which tasks are assigned to me?" or "list my plans" by running the tool for you.
10
+
11
+ ## Requirements
12
+ - Microsoft Edge
13
+ - [uv](https://docs.astral.sh/uv/) (for `uvx`), Python 3.10+
14
+
15
+ ## Usage
16
+ ```
17
+ uvx dvm-planner launch # start Edge (CDP port 19222, profile ~/.dvm-planner/edge-profile)
18
+ uvx dvm-planner plans # list plans (recent + favorites)
19
+ uvx dvm-planner mytasks [--summary] # tasks assigned to me, grouped by plan
20
+ uvx dvm-planner usertasks "Giampaolo" --with-due # tasks assigned to someone else (name or e-mail)
21
+ uvx dvm-planner tasks <planId|URL> # buckets + tasks of one plan
22
+ uvx dvm-planner tasks --all -o all.json # every listed plan
23
+ uvx dvm-planner update-task "North Star Layers" --due 2026-12-31 --comment "Updated" # id or title fragment
24
+ ```
25
+ uvx dvm-planner remind --list [--json] # my open tasks with due dates, numbered
26
+ uvx dvm-planner remind --select 1,3-5 # Outlook event "Planner: <task>" on the due date (09:00, 30 min, reminder 1 day before)
27
+ uvx dvm-planner remind --all --dry-run # or --task "title"; non-interactive when not on a TTY
28
+ uvx dvm-planner remind --sync # after due dates change: move matching events to the new date
29
+ ```
30
+ `remind` options: `--at HH:MM`, `--duration MIN`, `--reminder-minutes N`, `--on DATE`, `--show-as`,
31
+ `--include-past`, `--include-done`, `--include-no-due`. Past dates and existing events are skipped.
32
+ With no selector on a terminal it prompts for numbers.
33
+
34
+ `update-task` options: `--due YYYY-MM-DD|none`, `--notes HTML`, `--add-checklist TEXT` (repeatable),
35
+ `--comment TEXT`, `--patch JSON` (raw body, for fields captured from the UI - see docs).
36
+ Options: `--port`, `--profile`, `--edge-path`, `-o/--output`. On first run sign in to Planner in the
37
+ Edge window that opens (SSO usually works automatically); the profile is reused afterwards.
38
+
39
+ Notes: `plans` covers recent/favorite plans only; due dates are in `dueDateTime.date` (`dueUtcDateTime` is legacy/null);
40
+ tokens last about an hour and are recaptured on each run.
41
+ How it works: [docs/planner-cdp.md](docs/planner-cdp.md).
42
+
43
+ ## Use with GitHub Copilot CLI
44
+ ```
45
+ uvx dvm-planner --update-skills copilot # installs to ~/.copilot/skills/dvm-planner
46
+ ```
47
+ Restart/reload Copilot CLI, then ask e.g. *"List the tasks assigned to me in Planner"*; the
48
+ `dvm-planner` skill is picked up automatically.
49
+
50
+ ## Use with Claude Code
51
+ ```
52
+ uvx dvm-planner --update-skills claude # installs to ~/.claude/skills/dvm-planner
53
+ ```
54
+ Start a new Claude Code session and ask the same kind of question.
55
+
56
+ `uvx dvm-planner --update-skills` (no value) installs for both. Re-run it after upgrading
57
+ (`uvx dvm-planner@latest --update-skills`) to refresh the skill.
58
+
59
+ ## Development & releases
60
+ Skill source: `src/dvm_planner/skills/dvm-planner/SKILL.md` (bundled in the wheel).
61
+ Every push to `main` tags the next `vX.Y.Z` and publishes to PyPI via Trusted Publishing
62
+ (one-time setup: PyPI trusted publisher for this repo, workflow `release.yml`, environment `pypi`).
63
+ The version is derived from git tags (hatch-vcs).
64
+
65
+ ### Keeping docs current (required)
66
+ On every major change (new/changed command or option, new data source/endpoint, packaging or release
67
+ change) update **in the same commit**: this README, `docs/planner-cdp.md`, and the skill
68
+ `src/dvm_planner/skills/dvm-planner/SKILL.md`. These rules are also in `AGENTS.md`.
@@ -0,0 +1,82 @@
1
+ # Reading Microsoft Planner tasks through the browser (CDP)
2
+
3
+ ## 1. Start Edge with CDP
4
+ A separate profile folder is required (Edge ignores the debug port for the default profile):
5
+
6
+ ```powershell
7
+ msedge --remote-debugging-port=19222 --user-data-dir=<folder>\edge-profile --remote-allow-origins=* `
8
+ "https://planner.cloud.microsoft/ui/web/plan/<planId>/view/board?tid=<tenantId>"
9
+ ```
10
+ SSO signs in automatically; otherwise sign in once (profile persists).
11
+ `http://127.0.0.1:19222/json/list` lists tabs with their `webSocketDebuggerUrl`.
12
+
13
+ ## 2. Discover the API
14
+ Connect to the Planner page websocket, send `Network.enable` then `Page.reload`, and watch
15
+ `Network.requestWillBeSent`. The UI calls a private OData API:
16
+
17
+ `https://api.planner.svc.cloud.microsoft/taskapi/v4.0`
18
+
19
+ with header `Authorization: Bearer <token>` (the token is not stored in a readable cookie; read it from the
20
+ request headers of any call to that host). Other hosts (graph.microsoft.com, project.microsoft.com) get their
21
+ own tokens, which do **not** work for taskapi.
22
+
23
+ ## 3. Endpoints
24
+ | Purpose | Request |
25
+ |---|---|
26
+ | Plans (recent) | `GET /users('me')/recentPlans` |
27
+ | Plans (favorites) | `GET /users('me')/favoritePlans` |
28
+ | One plan | `GET /plans('{planId}')` (`?$expand=planView/categories,links,contexts` adds labels) |
29
+ | Buckets | `GET /plans('{planId}')/buckets` |
30
+ | Tasks | `GET /plans('{planId}')/tasks?$expand=checklist,links,userAssignments,customFieldValues` |
31
+ | Custom fields | `GET /plans('{planId}')/customFieldDefinitions?$expand=choiceOptions` |
32
+ | Goals | `GET /plans('{planId}')/goals` |
33
+
34
+ Notes: `/users('me')/plans` and `/plans` without a filter fail (404/405). Responses are paged with
35
+ `@odata.nextLink`. Plan id is the segment after `/plan/` in the UI URL.
36
+
37
+ ## 4. Task fields
38
+ Each task includes `id`, `displayName`, `bucketId`, `percentComplete`, `status`, `priority`,
39
+ `startDateTime`, `dueDateTime`, `notes` (html), `creationInfo`, `lastModifiedBy`,
40
+ `planView.appliedCategoryIds` (labels), plus expanded `checklist`, `links`, `userAssignments`,
41
+ `customFieldValues`. Tokens expire after ~1h; recapture by reloading the tab.
42
+
43
+ ## 5. Writing: capture what the UI sends
44
+ Guessing write payloads fails silently (e.g. PATCHing `dueUtcDateTime` returns 200 but changes nothing).
45
+ Record the real calls instead: attach CDP to the Planner tab, `Network.enable`, and log every
46
+ non-GET request to `api.planner.svc.cloud.microsoft` with `request.postData` while you perform the action in the UI.
47
+ Writes need headers `If-Match: <task @odata.etag>` (GET the task first), `OData-Version: 4.01`,
48
+ `Content-Type: application/json`, and `Prefer: return=representation`.
49
+
50
+ | Action | Request (all under `/taskapi/v4.0`) |
51
+ |---|---|
52
+ | Set due date | `PATCH /tasks('{id}')?$expand=checklist,links,userAssignments,customFieldValues` body `{"dueDateTime":{"date":"2026-12-18"}}` (`null` clears) |
53
+ | Notes | same PATCH, `{"notes":{"content":"<div>..</div>","contentType":"html"}}` |
54
+ | Add checklist item | same PATCH, `{"checklist@delta":[{"displayName":"..","isChecked":false,"orderHint":" <9223372036854775807 - .NET ticks>P,!"}]}` |
55
+ | Comment | `POST /tasks('{id}')/messages` `{"messageType":"richTextHtml","content":"<div>..</div>","properties":{"mentions":[]}}` |
56
+
57
+ `timeZone` is read-only. Read and write both use `dueDateTime` (`{date, time, timezone, isTimeSpecified}`); `dueUtcDateTime` is legacy and is usually null.
58
+
59
+ ## 6. Other people's tasks
60
+ `/users('{otherId}')/tasks` returns 403, so dvm-planner scans `/plans('{id}')/tasks` for the plans you can see
61
+ (recent/favorite plus plans holding your tasks) and filters `userAssignments` (a list of `{id: <user GUID without dashes>, ...}`). The user id is resolved
62
+ with Microsoft Graph `GET /v1.0/users?$search="displayName:..."` (header `ConsistencyLevel: eventual`), using the
63
+ `graph.microsoft.com` bearer token captured from the same page load.
64
+
65
+ ## 7. Calendar reminders (Outlook on the web)
66
+ Graph tokens from Planner are read-only for calendars, so events are created with OWA's own API, found by
67
+ recording the browser while creating an event manually (browser-level `Target.setAutoAttach` with
68
+ `flatten: true`, then `Network.enable` per attached session; the Planner tab alone sees nothing).
69
+ - `POST https://outlook.cloud.microsoft/owa/service.svc?action=<Action>&app=Calendar`
70
+ - Headers: `Authorization: Bearer` and `X-AnchorMailbox` (both copied from the Outlook tab's own `service.svc`
71
+ request), `Action: <Action>`, `Prefer: IdType="ImmutableId"`, JSON content type.
72
+ - Body: `{"Header":{"__type":"JsonRequestHeaders:#Exchange","RequestServerVersion":"V2018_01_08","TimeZoneContext":{...}},"Body":{...}}`
73
+ - `CreateCalendarEvent`: `CreateItemRequest` with a `CalendarItem` (`Subject`, HTML `Body`, `Start`/`End` as
74
+ `YYYY-MM-DDTHH:MM:SS.000`, time zone ids, `ReminderIsSet`, `ReminderMinutesBeforeStart`, `FreeBusyType`),
75
+ `SavedItemFolderId` = distinguished `calendar`, `SendMeetingInvitations: SendToNone`.
76
+ - `FindItem` + `CalendarView` (use `BaseShape: Default`; filter results by `Start`) for duplicate checks.
77
+ - `DeleteItem` (`ItemId {Id, ChangeKey}`, `MoveToDeletedItems`) removes an event. `remind --sync` re-dates an
78
+ event by creating it on the new date and deleting the old one (events are matched by subject `Planner: <title>`).
79
+
80
+ ## 8. Automation
81
+ `dvm-planner` implements these steps: `launch`, `plans`, `mytasks`, `usertasks`, `tasks`, `update-task`, `remind`.
82
+
@@ -0,0 +1,20 @@
1
+ [build-system]
2
+ requires = ["hatchling", "hatch-vcs"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "dvm-planner"
7
+ dynamic = ["version"]
8
+ description = "Extract Microsoft Planner plans and tasks as JSON via an Edge browser (CDP)"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ dependencies = ["httpx>=0.27", "websockets>=12"]
12
+
13
+ [project.scripts]
14
+ dvm-planner = "dvm_planner.cli:main"
15
+
16
+ [tool.hatch.version]
17
+ source = "vcs"
18
+
19
+ [tool.hatch.build.targets.wheel]
20
+ packages = ["src/dvm_planner"]
@@ -0,0 +1,8 @@
1
+ """Extract Microsoft Planner plans and tasks through an Edge browser using CDP."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ try:
6
+ __version__ = version("dvm-planner")
7
+ except PackageNotFoundError: # running from a source checkout
8
+ __version__ = "0.0.0"
@@ -0,0 +1,152 @@
1
+ """Launch Edge with remote debugging and capture the Planner bearer token via CDP."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import shutil
8
+ import subprocess
9
+ import time
10
+ from pathlib import Path
11
+
12
+ import httpx
13
+ from websockets.sync.client import connect
14
+
15
+ PLANNER_HOME = "https://planner.cloud.microsoft/ui/web/"
16
+ API_HOST = "api.planner.svc.cloud.microsoft"
17
+ OUTLOOK_HOST = "outlook.cloud.microsoft"
18
+ OUTLOOK_CALENDAR = f"https://{OUTLOOK_HOST}/calendar/view/week"
19
+ DEFAULT_PORT = 19222
20
+ DEFAULT_PROFILE = Path.home() / ".dvm-planner" / "edge-profile"
21
+
22
+ _EDGE_CANDIDATES = [
23
+ r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe",
24
+ r"C:\Program Files\Microsoft\Edge\Application\msedge.exe",
25
+ "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
26
+ "/usr/bin/microsoft-edge",
27
+ ]
28
+
29
+
30
+ def find_edge() -> str:
31
+ found = shutil.which("msedge") or shutil.which("microsoft-edge")
32
+ if found:
33
+ return found
34
+ for c in _EDGE_CANDIDATES:
35
+ if os.path.exists(c):
36
+ return c
37
+ raise FileNotFoundError("Microsoft Edge not found; pass --edge-path")
38
+
39
+
40
+ def cdp_alive(port: int) -> bool:
41
+ try:
42
+ return httpx.get(f"http://127.0.0.1:{port}/json/version", timeout=2).status_code == 200
43
+ except httpx.HTTPError:
44
+ return False
45
+
46
+
47
+ def launch_edge(port: int = DEFAULT_PORT, profile: Path = DEFAULT_PROFILE,
48
+ edge_path: str | None = None, url: str = PLANNER_HOME) -> bool:
49
+ """Start Edge with CDP enabled. Returns False if a browser already listens on the port."""
50
+ if cdp_alive(port):
51
+ return False
52
+ profile.mkdir(parents=True, exist_ok=True)
53
+ subprocess.Popen(
54
+ [edge_path or find_edge(), f"--remote-debugging-port={port}",
55
+ f"--user-data-dir={profile}", "--remote-allow-origins=*", "--no-first-run", url],
56
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
57
+ )
58
+ for _ in range(60):
59
+ if cdp_alive(port):
60
+ return True
61
+ time.sleep(0.5)
62
+ raise TimeoutError(f"Edge did not expose CDP on port {port}")
63
+
64
+
65
+ class Cdp:
66
+ """Minimal synchronous CDP session over a page websocket."""
67
+
68
+ def __init__(self, ws_url: str):
69
+ self.ws = connect(ws_url, max_size=None)
70
+ self._id = 0
71
+
72
+ def call(self, method: str, **params):
73
+ self._id += 1
74
+ self.ws.send(json.dumps({"id": self._id, "method": method, "params": params}))
75
+ return self._id
76
+
77
+ def events(self, timeout: float):
78
+ """Yield CDP messages until `timeout` seconds have elapsed."""
79
+ end = time.monotonic() + timeout
80
+ while (left := end - time.monotonic()) > 0:
81
+ try:
82
+ yield json.loads(self.ws.recv(timeout=min(left, 1)))
83
+ except TimeoutError:
84
+ continue
85
+
86
+ def close(self):
87
+ self.ws.close()
88
+
89
+
90
+ def _planner_tab(port: int) -> dict:
91
+ base = f"http://127.0.0.1:{port}"
92
+ for t in httpx.get(f"{base}/json/list").json():
93
+ if t["type"] == "page" and "planner.cloud.microsoft" in t["url"]:
94
+ return t
95
+ return httpx.put(f"{base}/json/new?{PLANNER_HOME}").json()
96
+
97
+
98
+ def capture_outlook(port: int = DEFAULT_PORT, timeout: float = 60) -> tuple[str, str]:
99
+ """Reload an Outlook calendar tab (opening one if needed); return (Authorization, X-AnchorMailbox)
100
+ as sent by Outlook on the web to its owa/service.svc endpoint."""
101
+ base = f"http://127.0.0.1:{port}"
102
+ tab = next((t for t in httpx.get(f"{base}/json/list").json()
103
+ if t["type"] == "page" and OUTLOOK_HOST in t["url"]), None)
104
+ tab = tab or httpx.put(f"{base}/json/new?{OUTLOOK_CALENDAR}").json()
105
+ cdp = Cdp(tab["webSocketDebuggerUrl"])
106
+ try:
107
+ cdp.call("Network.enable")
108
+ cdp.call("Page.reload")
109
+ for msg in cdp.events(timeout):
110
+ if msg.get("method") != "Network.requestWillBeSent":
111
+ continue
112
+ req = msg["params"]["request"]
113
+ if "/owa/service.svc" not in req["url"]:
114
+ continue
115
+ h = {k.lower(): v for k, v in req["headers"].items()}
116
+ if "authorization" in h and "x-anchormailbox" in h:
117
+ return h["authorization"], h["x-anchormailbox"]
118
+ finally:
119
+ cdp.close()
120
+ raise TimeoutError("No Outlook token seen. Is the browser signed in to Outlook on the web?")
121
+
122
+
123
+ def capture_tokens(port: int = DEFAULT_PORT, hosts: tuple[str, ...] = (API_HOST,),
124
+ timeout: float = 60) -> dict[str, str]:
125
+ """Reload the Planner tab and return the Authorization header seen for each host in `hosts`."""
126
+ tab = _planner_tab(port)
127
+ cdp = Cdp(tab["webSocketDebuggerUrl"])
128
+ found: dict[str, str] = {}
129
+ try:
130
+ cdp.call("Network.enable")
131
+ cdp.call("Page.reload")
132
+ for msg in cdp.events(timeout):
133
+ if msg.get("method") != "Network.requestWillBeSent":
134
+ continue
135
+ req = msg["params"]["request"]
136
+ host = req["url"].split("/")[2] if "//" in req["url"] else ""
137
+ if host not in hosts or host in found:
138
+ continue
139
+ for k, v in req["headers"].items():
140
+ if k.lower() == "authorization":
141
+ found[host] = v
142
+ if len(found) == len(hosts):
143
+ return found
144
+ finally:
145
+ cdp.close()
146
+ missing = [h for h in hosts if h not in found]
147
+ raise TimeoutError(f"No token seen for {missing}. Is the browser signed in to Planner?")
148
+
149
+
150
+ def capture_token(port: int = DEFAULT_PORT, timeout: float = 60) -> str:
151
+ """Return the Authorization header sent to the Planner API."""
152
+ return capture_tokens(port, (API_HOST,), timeout)[API_HOST]
@@ -0,0 +1,191 @@
1
+ """Export Microsoft Planner plans and tasks as JSON via an Edge browser (CDP)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import re
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ from . import __version__
12
+ from .browser import API_HOST, DEFAULT_PORT, DEFAULT_PROFILE, capture_outlook, capture_tokens, launch_edge
13
+ from .outlook import OutlookClient
14
+ from .reminders import candidates, create_reminders, format_table, prompt_selection, select, sync_reminders
15
+ from .planner import GRAPH_HOST, PlannerClient
16
+ from .installer import update_skills
17
+
18
+
19
+ def _plan_id(value: str) -> str:
20
+ m = re.search(r"/plan/([^/?#]+)", value)
21
+ return m.group(1) if m else value
22
+
23
+
24
+ def _client(args) -> PlannerClient:
25
+ launch_edge(args.port, args.profile, args.edge_path)
26
+ tokens = capture_tokens(args.port, (API_HOST, GRAPH_HOST))
27
+ return PlannerClient(tokens[API_HOST], tokens[GRAPH_HOST])
28
+
29
+
30
+ def _emit(data, out: str | None):
31
+ text = json.dumps(data, indent=2, ensure_ascii=False)
32
+ if out:
33
+ Path(out).write_text(text, encoding="utf-8")
34
+ print(f"wrote {out}", file=sys.stderr)
35
+ else:
36
+ print(text)
37
+
38
+
39
+ def _remind(args, p) -> int:
40
+ rows = candidates(_client(args), args.include_done, args.include_no_due)
41
+ public = [{k: v for k, v in r.items() if k not in ("task", "tenantId")} for r in rows]
42
+ if args.sync:
43
+ auth, anchor = capture_outlook(args.port)
44
+ _emit(sync_reminders(OutlookClient(auth, anchor), rows, reminder_minutes=args.reminder_minutes,
45
+ show_as=args.show_as, dry_run=args.dry_run), None)
46
+ return 0
47
+ if args.list:
48
+ if args.json:
49
+ _emit(public, None)
50
+ else:
51
+ print(format_table(rows))
52
+ return 0
53
+ try:
54
+ if args.all or args.select or args.task:
55
+ chosen = select(rows, args.all, args.select, args.task)
56
+ elif sys.stdin.isatty():
57
+ chosen = prompt_selection(rows)
58
+ else:
59
+ p.error("non-interactive: give --all, --select or --task (use --list first)")
60
+ except ValueError as e:
61
+ p.error(str(e))
62
+ if not chosen:
63
+ print("nothing selected", file=sys.stderr)
64
+ return 0
65
+ if (args.include_no_due and not args.on) and any(not r["due"] for r in chosen):
66
+ p.error("tasks without a due date need --on YYYY-MM-DD")
67
+ auth, anchor = capture_outlook(args.port)
68
+ results = create_reminders(OutlookClient(auth, anchor), chosen, at=args.at, duration=args.duration,
69
+ reminder_minutes=args.reminder_minutes, on=args.on, show_as=args.show_as,
70
+ dry_run=args.dry_run, include_past=args.include_past)
71
+ _emit(results, None)
72
+ return 0
73
+
74
+
75
+ def main(argv: list[str] | None = None) -> int:
76
+ p = argparse.ArgumentParser(prog="dvm-planner", description=__doc__)
77
+ p.add_argument("--version", action="version", version=__version__)
78
+ p.add_argument("--port", type=int, default=DEFAULT_PORT, help="CDP port")
79
+ p.add_argument("--profile", type=Path, default=DEFAULT_PROFILE, help="Edge user-data-dir")
80
+ p.add_argument("--edge-path", help="Path to msedge executable")
81
+ p.add_argument("--update-skills", nargs="?", const="all", choices=["all", "copilot", "claude"],
82
+ metavar="{all,copilot,claude}",
83
+ help="Install/refresh the dvm-planner skill for GitHub Copilot and/or Claude Code")
84
+ sub = p.add_subparsers(dest="cmd")
85
+
86
+ sub.add_parser("launch", help="Start Edge with CDP enabled and open Planner")
87
+ pl = sub.add_parser("plans", help="List plans as JSON")
88
+ pl.add_argument("-o", "--output")
89
+ rm = sub.add_parser("remind", help="List my tasks and create Outlook calendar reminders for selected ones")
90
+ rm.add_argument("--list", action="store_true", help="Only list candidate tasks (numbered)")
91
+ rm.add_argument("--all", action="store_true", help="Create reminders for all listed tasks")
92
+ rm.add_argument("--select", metavar="N,M-K", help="Numbers from --list (stable order by due date)")
93
+ rm.add_argument("--task", action="append", default=[], help="Task id or title fragment (repeatable)")
94
+ rm.add_argument("--include-done", action="store_true", help="Include 100%% complete tasks")
95
+ rm.add_argument("--include-no-due", action="store_true", help="Include tasks without a due date (needs --on)")
96
+ rm.add_argument("--on", metavar="YYYY-MM-DD", help="Event date (default: the task's due date)")
97
+ rm.add_argument("--at", default="09:00", metavar="HH:MM", help="Event start time (default 09:00)")
98
+ rm.add_argument("--duration", type=int, default=30, help="Event minutes (default 30)")
99
+ rm.add_argument("--reminder-minutes", type=int, default=1440, help="Reminder before start (default 1440 = 1 day)")
100
+ rm.add_argument("--show-as", default="Busy", choices=["Busy", "Free", "Tentative", "OOF"])
101
+ rm.add_argument("--include-past", action="store_true", help="Create events even if the date has passed")
102
+ rm.add_argument("--sync", action="store_true",
103
+ help="Move existing 'Planner: <task>' events to the task's current due date")
104
+ rm.add_argument("--dry-run", action="store_true")
105
+ rm.add_argument("--json", action="store_true", help="JSON output for --list")
106
+ ut = sub.add_parser("usertasks", help="Tasks assigned to another person (name or e-mail)")
107
+ ut.add_argument("user")
108
+ ut.add_argument("--plan", action="append", help="Limit to plan id/URL (repeatable)")
109
+ ut.add_argument("--with-due", action="store_true", help="Only tasks that have a due date")
110
+ ut.add_argument("-o", "--output")
111
+ mt = sub.add_parser("mytasks", help="Tasks assigned to me, grouped by plan (JSON)")
112
+ mt.add_argument("-o", "--output")
113
+ mt.add_argument("--summary", action="store_true", help="Only plan names and task counts")
114
+ u = sub.add_parser("update-task", help="Update a task (due date, notes, checklist, comment)")
115
+ u.add_argument("task", help="Task id, or part of the title of one of my tasks")
116
+ u.add_argument("--due", metavar="YYYY-MM-DD|none", help="Set or clear the due date")
117
+ u.add_argument("--notes", help="Replace notes (HTML)")
118
+ u.add_argument("--add-checklist", action="append", default=[], metavar="TEXT")
119
+ u.add_argument("--comment", help="Post a comment")
120
+ u.add_argument("--patch", metavar="JSON", help="Raw PATCH body, as sent by the Planner UI")
121
+ t = sub.add_parser("tasks", help="Export plan tasks (with buckets) as JSON")
122
+ t.add_argument("plan", nargs="*", help="Plan ids or Planner URLs; omit with --all")
123
+ t.add_argument("--all", action="store_true", help="Export every listed plan")
124
+ t.add_argument("-o", "--output")
125
+
126
+ args = p.parse_args(argv)
127
+ if args.update_skills:
128
+ targets = None if args.update_skills == "all" else [args.update_skills]
129
+ for d in update_skills(targets):
130
+ print(f"installed skill -> {d}")
131
+ return 0
132
+ if not args.cmd:
133
+ p.error("a command is required (launch, plans, mytasks, tasks) or --update-skills")
134
+ if args.cmd == "launch":
135
+ started = launch_edge(args.port, args.profile, args.edge_path)
136
+ print("started Edge" if started else "CDP already available", f"on port {args.port}")
137
+ return 0
138
+
139
+ if args.cmd == "tasks" and not args.all and not args.plan:
140
+ p.error("give plan ids/URLs or --all")
141
+ if args.cmd == "remind":
142
+ return _remind(args, p)
143
+ client = _client(args)
144
+ if args.cmd == "plans":
145
+ _emit([{"id": x["id"], "displayName": x.get("displayName"),
146
+ "lastModifiedDateTime": x.get("lastModifiedDateTime")}
147
+ for x in client.list_plans()], args.output)
148
+ elif args.cmd == "usertasks":
149
+ users = client.find_users(args.user)
150
+ if len(users) != 1:
151
+ p.error(f"{len(users)} users match {args.user!r}: "
152
+ + "; ".join(f"{u['displayName']} <{u['mail']}>" for u in users))
153
+ tasks = client.user_tasks(users[0]["id"], [_plan_id(x) for x in args.plan] if args.plan else None)
154
+ if args.with_due:
155
+ tasks = [t for t in tasks if (t.get("dueDateTime") or {}).get("date")]
156
+ tasks.sort(key=lambda t: ((t.get("dueDateTime") or {}).get("date") or "9999", t["displayName"]))
157
+ _emit({"user": users[0], "taskCount": len(tasks), "tasks": tasks}, args.output)
158
+ elif args.cmd == "update-task":
159
+ task_id = args.task
160
+ if not re.fullmatch(r"[\w-]{20,}", task_id):
161
+ hits = client.find_my_tasks(task_id)
162
+ if len(hits) != 1:
163
+ p.error(f"{len(hits)} of my tasks match {task_id!r}: "
164
+ + "; ".join(f"{t['displayName']} ({t['id']})" for t in hits))
165
+ task_id = hits[0]["id"]
166
+ if args.due:
167
+ if args.due != "none" and not re.fullmatch(r"\d{4}-\d{2}-\d{2}", args.due):
168
+ p.error("--due must be YYYY-MM-DD or none")
169
+ client.set_due_date(task_id, None if args.due == "none" else args.due)
170
+ if args.notes:
171
+ client.set_notes(task_id, args.notes)
172
+ for item in args.add_checklist:
173
+ client.add_checklist_item(task_id, item)
174
+ if args.patch:
175
+ client.patch_task(task_id, json.loads(args.patch))
176
+ if args.comment:
177
+ client.add_comment(task_id, args.comment)
178
+ _emit(client.get_task(task_id), None)
179
+ elif args.cmd == "mytasks":
180
+ data = client.my_tasks_by_plan()
181
+ if args.summary:
182
+ data = [{k: v for k, v in x.items() if k != "tasks"} for x in data]
183
+ _emit(data, args.output)
184
+ else:
185
+ plans = client.list_plans() if args.all else [client.get_plan(_plan_id(x)) for x in args.plan]
186
+ _emit([client.plan_export(x) for x in plans], args.output)
187
+ return 0
188
+
189
+
190
+ if __name__ == "__main__":
191
+ raise SystemExit(main())
@@ -0,0 +1,26 @@
1
+ """Install the bundled agent skill for GitHub Copilot CLI and Claude Code."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import shutil
6
+ from importlib.resources import as_file, files
7
+ from pathlib import Path
8
+
9
+ SKILL_NAME = "dvm-planner"
10
+ TARGETS = {
11
+ "copilot": Path.home() / ".copilot" / "skills",
12
+ "claude": Path.home() / ".claude" / "skills",
13
+ }
14
+
15
+
16
+ def update_skills(targets: list[str] | None = None) -> list[Path]:
17
+ """Copy the bundled skill into each target's skills directory, replacing any old copy."""
18
+ installed = []
19
+ with as_file(files("dvm_planner") / "skills" / SKILL_NAME) as src:
20
+ for name in targets or list(TARGETS):
21
+ dest = TARGETS[name] / SKILL_NAME
22
+ if dest.exists():
23
+ shutil.rmtree(dest)
24
+ shutil.copytree(src, dest)
25
+ installed.append(dest)
26
+ return installed
@@ -0,0 +1,87 @@
1
+ """Create Outlook calendar reminders through Outlook on the web's own OWA JSON API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import html
6
+ from datetime import date, datetime, timedelta
7
+
8
+ import httpx
9
+
10
+ SERVICE = "https://outlook.cloud.microsoft/owa/service.svc"
11
+ TZ = "W. Europe Standard Time"
12
+ FMT = "%Y-%m-%dT%H:%M:%S.000"
13
+
14
+
15
+ def planner_task_url(plan_id: str, task_id: str, tenant_id: str) -> str:
16
+ return f"https://planner.cloud.microsoft/webui/plan/{plan_id}/view/board/task/{task_id}?tid={tenant_id}"
17
+
18
+
19
+ class OutlookClient:
20
+ def __init__(self, authorization: str, anchor: str, timezone: str = TZ):
21
+ self.tz = timezone
22
+ self.headers = {"Authorization": authorization, "X-AnchorMailbox": anchor,
23
+ "Content-Type": "application/json; charset=utf-8",
24
+ "Prefer": 'IdType="ImmutableId"'}
25
+
26
+ def _call(self, action: str, body: dict) -> dict:
27
+ req = {"Header": {"__type": "JsonRequestHeaders:#Exchange", "RequestServerVersion": "V2018_01_08",
28
+ "TimeZoneContext": {"__type": "TimeZoneContext:#Exchange",
29
+ "TimeZoneDefinition": {"__type": "TimeZoneDefinitionType:#Exchange",
30
+ "Id": self.tz}}},
31
+ "Body": body}
32
+ r = httpx.post(f"{SERVICE}?action={action}&app=Calendar", json=req, timeout=60,
33
+ headers={**self.headers, "Action": action})
34
+ r.raise_for_status()
35
+ return r.json()["Body"]
36
+
37
+ def events_between(self, first: date, last: date) -> list[dict]:
38
+ """Events starting on first..last inclusive."""
39
+ body = self._call("FindItem", {
40
+ "__type": "FindItemRequest:#Exchange",
41
+ "ItemShape": {"__type": "ItemResponseShape:#Exchange", "BaseShape": "Default"},
42
+ "CalendarView": {"__type": "CalendarView:#Exchange", "StartDate": first.strftime(FMT),
43
+ "EndDate": (last + timedelta(days=1)).strftime(FMT)},
44
+ "ParentFolderIds": [{"__type": "DistinguishedFolderId:#Exchange", "Id": "calendar"}],
45
+ "Traversal": "Shallow"})
46
+ items = body["ResponseMessages"]["Items"][0]["RootFolder"]["Items"]
47
+ # the service may return more than the requested window, so filter by start date
48
+ return [i for i in items if first.isoformat() <= str(i.get("Start", ""))[:10] <= last.isoformat()]
49
+
50
+ def events_on(self, day: date) -> list[dict]:
51
+ return self.events_between(day, day)
52
+
53
+ def find_by_subject(self, day: date, subject: str) -> dict | None:
54
+ return next((e for e in self.events_on(day) if e.get("Subject") == subject), None)
55
+
56
+ def create_event(self, subject: str, body_html: str, start: datetime, minutes: int,
57
+ reminder_minutes: int, show_as: str = "Busy") -> dict:
58
+ item = {"__type": "CalendarItem:#Exchange", "Subject": subject,
59
+ "Body": {"BodyType": "HTML", "Value": body_html},
60
+ "Start": start.strftime(FMT), "End": (start + timedelta(minutes=minutes)).strftime(FMT),
61
+ "StartTimeZoneId": self.tz, "EndTimeZoneId": self.tz, "IsAllDayEvent": False,
62
+ "FreeBusyType": show_as, "ReminderIsSet": True,
63
+ "ReminderMinutesBeforeStart": reminder_minutes, "Sensitivity": "Normal",
64
+ "IsResponseRequested": True}
65
+ body = self._call("CreateCalendarEvent", {
66
+ "__type": "CreateItemRequest:#Exchange", "Items": [item],
67
+ "SavedItemFolderId": {"__type": "TargetFolderId:#Exchange",
68
+ "BaseFolderId": {"__type": "DistinguishedFolderId:#Exchange", "Id": "calendar"}},
69
+ "ItemShape": {"__type": "ItemResponseShape:#Exchange", "BaseShape": "IdOnly"},
70
+ "SendMeetingInvitations": "SendToNone"})
71
+ msg = body["ResponseMessages"]["Items"][0]
72
+ if msg.get("ResponseClass") not in (None, "Success"):
73
+ raise RuntimeError(msg.get("MessageText") or str(msg))
74
+ return msg["Items"][0]["ItemId"]
75
+
76
+ def delete_event(self, item_id: dict) -> None:
77
+ self._call("DeleteItem", {
78
+ "__type": "DeleteItemRequest:#Exchange",
79
+ "ItemIds": [{"__type": "ItemId:#Exchange", "Id": item_id["Id"], "ChangeKey": item_id.get("ChangeKey")}],
80
+ "DeleteType": "MoveToDeletedItems", "SendMeetingCancellations": "SendToNone"})
81
+
82
+
83
+ def reminder_body(task: dict, plan_name: str, link: str) -> str:
84
+ due = (task.get("dueDateTime") or {}).get("date") or "-"
85
+ return (f'<div>Planner task: <a href="{html.escape(link)}">{html.escape(task["displayName"])}</a></div>'
86
+ f"<div>Plan: {html.escape(plan_name or '')}</div>"
87
+ f"<div>Due: {due} &middot; Progress: {task.get('percentComplete', 0)}%</div>")
@@ -0,0 +1,148 @@
1
+ """Planner taskapi client (the same internal API the Planner web UI uses)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import html
6
+ import time
7
+
8
+ import httpx
9
+
10
+ BASE = "https://api.planner.svc.cloud.microsoft/taskapi/v4.0"
11
+ TASK_EXPAND = "checklist,links,userAssignments,customFieldValues"
12
+
13
+
14
+ GRAPH_HOST = "graph.microsoft.com"
15
+
16
+
17
+ class PlannerClient:
18
+ def __init__(self, authorization: str, graph_authorization: str | None = None):
19
+ self.graph_auth = graph_authorization
20
+ self.http = httpx.Client(
21
+ headers={"Authorization": authorization, "Accept": "application/json"}, timeout=60
22
+ )
23
+
24
+ def find_users(self, query: str) -> list[dict]:
25
+ """Resolve a name/e-mail to Entra users via Microsoft Graph (needs the Graph token)."""
26
+ if not self.graph_auth:
27
+ raise RuntimeError("Graph token required (use capture_tokens with graph.microsoft.com)")
28
+ r = httpx.get(
29
+ "https://graph.microsoft.com/v1.0/users",
30
+ params={"$search": f'"displayName:{query}" OR "mail:{query}"',
31
+ "$select": "id,displayName,mail", "$top": "10"},
32
+ headers={"Authorization": self.graph_auth, "ConsistencyLevel": "eventual"},
33
+ timeout=60,
34
+ )
35
+ r.raise_for_status()
36
+ return r.json()["value"]
37
+
38
+ def user_tasks(self, user_id: str, plan_ids: list[str] | None = None) -> list[dict]:
39
+ """Tasks assigned to any user. The API has no per-user endpoint for others, so scan plans:
40
+ the given ones, else recent/favorite plans plus every plan holding one of my tasks."""
41
+ if plan_ids is None:
42
+ ids = {p["id"] for p in self.list_plans()} | {t["planId"] for t in self.my_tasks()}
43
+ plan_ids = sorted(ids)
44
+ wanted = user_id.replace("-", "").lower()
45
+ names = {p["id"]: p.get("displayName") for p in self.list_plans()}
46
+ out = []
47
+ for pid in plan_ids:
48
+ for t in self.tasks(pid):
49
+ # userAssignments is a list of {id: <user GUID without dashes>, ...}
50
+ if any(a.get("id", "").lower() == wanted for a in t.get("userAssignments") or []):
51
+ t["planName"] = names.get(pid) or self.get_plan(pid).get("displayName")
52
+ out.append(t)
53
+ return out
54
+
55
+ def _get_all(self, url: str) -> list[dict]:
56
+ items: list[dict] = []
57
+ while url:
58
+ r = self.http.get(url)
59
+ r.raise_for_status()
60
+ data = r.json()
61
+ items += data.get("value", [])
62
+ url = data.get("@odata.nextLink")
63
+ return items
64
+
65
+ def list_plans(self) -> list[dict]:
66
+ """Recent + favorite plans, de-duplicated by id."""
67
+ plans: dict[str, dict] = {}
68
+ for path in ("recentPlans", "favoritePlans"):
69
+ for p in self._get_all(f"{BASE}/users('me')/{path}"):
70
+ plans.setdefault(p["id"], p)
71
+ return list(plans.values())
72
+
73
+ def my_tasks(self) -> list[dict]:
74
+ """Tasks assigned to the signed-in user, across all plans."""
75
+ return self._get_all(f"{BASE}/users('me')/tasks?$expand={TASK_EXPAND}")
76
+
77
+ def my_tasks_by_plan(self) -> list[dict]:
78
+ names = {p["id"]: p.get("displayName") for p in self.list_plans()}
79
+ grouped: dict[str, list[dict]] = {}
80
+ for t in self.my_tasks():
81
+ grouped.setdefault(t["planId"], []).append(t)
82
+ return [
83
+ {"id": pid, "displayName": names.get(pid) or self.get_plan(pid).get("displayName"),
84
+ "taskCount": len(ts), "tasks": ts}
85
+ for pid, ts in sorted(grouped.items(), key=lambda kv: -len(kv[1]))
86
+ ]
87
+
88
+ def get_task(self, task_id: str) -> dict:
89
+ r = self.http.get(f"{BASE}/tasks('{task_id}')?$expand={TASK_EXPAND}")
90
+ r.raise_for_status()
91
+ return r.json()
92
+
93
+ def find_my_tasks(self, text: str) -> list[dict]:
94
+ return [t for t in self.my_tasks() if text.lower() in t["displayName"].lower()]
95
+
96
+ def patch_task(self, task_id: str, changes: dict) -> dict:
97
+ """PATCH a task the way the Planner UI does (needs the current ETag + OData 4.01)."""
98
+ etag = self.get_task(task_id)["@odata.etag"]
99
+ r = self.http.patch(
100
+ f"{BASE}/tasks('{task_id}')?$expand={TASK_EXPAND}",
101
+ headers={"If-Match": etag, "Prefer": "return=representation",
102
+ "OData-Version": "4.01", "Content-Type": "application/json"},
103
+ json=changes,
104
+ )
105
+ r.raise_for_status()
106
+ return r.json()
107
+
108
+ def set_due_date(self, task_id: str, date: str | None) -> dict:
109
+ """`date` is YYYY-MM-DD, or None to clear."""
110
+ return self.patch_task(task_id, {"dueDateTime": {"date": date} if date else None})
111
+
112
+ def set_notes(self, task_id: str, html: str) -> dict:
113
+ return self.patch_task(task_id, {"notes": {"content": html, "contentType": "html"}})
114
+
115
+ def add_checklist_item(self, task_id: str, title: str) -> dict:
116
+ # Planner order hints are inverted .NET ticks.
117
+ ticks = int(time.time() * 10_000_000) + 621_355_968_000_000_000
118
+ item = {"displayName": title, "isChecked": False,
119
+ "orderHint": f" {9223372036854775807 - ticks}P,!"}
120
+ return self.patch_task(task_id, {"checklist@delta": [item]})
121
+
122
+ def add_comment(self, task_id: str, text: str) -> dict:
123
+ body = {"messageType": "richTextHtml", "content": f"<div>{html.escape(text)}</div>",
124
+ "properties": {"mentions": []}}
125
+ r = self.http.post(f"{BASE}/tasks('{task_id}')/messages",
126
+ headers={"OData-Version": "4.01"}, json=body)
127
+ r.raise_for_status()
128
+ return r.json()
129
+
130
+ def get_plan(self, plan_id: str) -> dict:
131
+ r = self.http.get(f"{BASE}/plans('{plan_id}')")
132
+ r.raise_for_status()
133
+ return r.json()
134
+
135
+ def buckets(self, plan_id: str) -> list[dict]:
136
+ return self._get_all(f"{BASE}/plans('{plan_id}')/buckets")
137
+
138
+ def tasks(self, plan_id: str) -> list[dict]:
139
+ return self._get_all(f"{BASE}/plans('{plan_id}')/tasks?$expand={TASK_EXPAND}")
140
+
141
+ def plan_export(self, plan: dict) -> dict:
142
+ pid = plan["id"]
143
+ return {
144
+ "id": pid,
145
+ "displayName": plan.get("displayName"),
146
+ "buckets": self.buckets(pid),
147
+ "tasks": self.tasks(pid),
148
+ }
@@ -0,0 +1,140 @@
1
+ """List my Planner tasks and create Outlook calendar reminders for selected ones."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import sys
7
+ from datetime import date, datetime, timedelta
8
+
9
+ from .outlook import OutlookClient, planner_task_url, reminder_body
10
+ from .planner import PlannerClient
11
+
12
+
13
+ def candidates(client: PlannerClient, include_done: bool = False, include_no_due: bool = False) -> list[dict]:
14
+ """My tasks as numbered rows sorted by due date (stable order so `--select` numbers are repeatable)."""
15
+ names = {p["id"]: p.get("displayName") for p in client.list_plans()}
16
+ rows = []
17
+ for t in client.my_tasks():
18
+ due = (t.get("dueDateTime") or {}).get("date")
19
+ if (t.get("percentComplete") == 100 and not include_done) or (not due and not include_no_due):
20
+ continue
21
+ plan = names.get(t["planId"]) or client.get_plan(t["planId"]).get("displayName")
22
+ names[t["planId"]] = plan
23
+ tenant = (((t.get("creationInfo") or {}).get("createdBy") or {}).get("user") or {}).get("tenantId", "")
24
+ rows.append({"id": t["id"], "title": t["displayName"], "plan": plan, "planId": t["planId"],
25
+ "due": due, "percentComplete": t.get("percentComplete", 0), "tenantId": tenant,
26
+ "task": t})
27
+ rows.sort(key=lambda r: (r["due"] or "9999", r["title"].lower(), r["id"]))
28
+ for i, r in enumerate(rows, 1):
29
+ r["n"] = i
30
+ return rows
31
+
32
+
33
+ def format_table(rows: list[dict]) -> str:
34
+ return "\n".join(f"{r['n']:>3} {r['due'] or '-':<10} {r['percentComplete']:>3}% {r['title'][:60]} [{r['plan']}]"
35
+ for r in rows)
36
+
37
+
38
+ def parse_numbers(spec: str, count: int) -> set[int]:
39
+ out: set[int] = set()
40
+ for part in spec.replace(" ", "").split(","):
41
+ m = re.fullmatch(r"(\d+)(?:-(\d+))?", part)
42
+ if not m:
43
+ raise ValueError(f"bad selection {part!r}")
44
+ lo, hi = int(m[1]), int(m[2] or m[1])
45
+ out.update(range(lo, hi + 1))
46
+ bad = [n for n in out if not 1 <= n <= count]
47
+ if bad:
48
+ raise ValueError(f"selection out of range 1-{count}: {sorted(bad)}")
49
+ return out
50
+
51
+
52
+ def select(rows: list[dict], all_: bool, numbers: str | None, tasks: list[str]) -> list[dict]:
53
+ if all_:
54
+ return rows
55
+ chosen: dict[str, dict] = {}
56
+ if numbers:
57
+ for n in parse_numbers(numbers, len(rows)):
58
+ chosen[rows[n - 1]["id"]] = rows[n - 1]
59
+ for q in tasks:
60
+ hits = [r for r in rows if r["id"] == q] or [r for r in rows if q.lower() in r["title"].lower()]
61
+ if len(hits) != 1:
62
+ raise ValueError(f"{len(hits)} tasks match {q!r}"
63
+ + (": " + "; ".join(f"{r['n']} {r['title']}" for r in hits) if hits else ""))
64
+ chosen[hits[0]["id"]] = hits[0]
65
+ return sorted(chosen.values(), key=lambda r: r["n"])
66
+
67
+
68
+ def prompt_selection(rows: list[dict]) -> list[dict]:
69
+ print(format_table(rows), file=sys.stderr)
70
+ ans = input("Create reminders for (numbers like 1,3-5, 'all', blank to cancel): ").strip()
71
+ if not ans:
72
+ return []
73
+ return rows if ans.lower() == "all" else select(rows, False, ans, [])
74
+
75
+
76
+ def sync_reminders(outlook: OutlookClient, rows: list[dict], *, reminder_minutes: int, show_as: str,
77
+ dry_run: bool, days: int = 400) -> list[dict]:
78
+ """Move existing `Planner: <title>` events whose date no longer matches the task's due date.
79
+
80
+ The event is deleted and recreated (same time of day and duration) on the new due date.
81
+ """
82
+ today = date.today()
83
+ events = [e for e in outlook.events_between(today - timedelta(days=30), today + timedelta(days=days))
84
+ if str(e.get("Subject", "")).startswith("Planner: ")]
85
+ by_subject: dict[str, list[dict]] = {}
86
+ for e in events:
87
+ by_subject.setdefault(e["Subject"], []).append(e)
88
+ results = []
89
+ for r in rows:
90
+ subject = f"Planner: {r['title']}"
91
+ found = by_subject.get(subject, [])
92
+ if not found:
93
+ continue
94
+ ev = found[0]
95
+ old = str(ev["Start"])[:10]
96
+ res = {"taskId": r["id"], "title": r["title"], "oldDate": old, "newDate": r["due"]}
97
+ if len(found) > 1:
98
+ res["status"] = "skipped (several events with this subject)"
99
+ elif old == r["due"]:
100
+ continue
101
+ elif datetime.fromisoformat(r["due"] + "T00:00") < datetime.combine(today, datetime.min.time()):
102
+ res["status"] = "skipped (new date in the past)"
103
+ elif dry_run:
104
+ res["status"] = "dry-run (would move)"
105
+ else:
106
+ s = datetime.fromisoformat(str(ev["Start"])[:19])
107
+ e_ = datetime.fromisoformat(str(ev["End"])[:19])
108
+ new_start = datetime.combine(date.fromisoformat(r["due"]), s.time())
109
+ link = planner_task_url(r["planId"], r["id"], r["tenantId"])
110
+ outlook.create_event(subject, reminder_body(r["task"], r["plan"], link), new_start,
111
+ int((e_ - s).total_seconds() // 60), reminder_minutes, show_as)
112
+ outlook.delete_event(ev["ItemId"])
113
+ res["status"] = "moved"
114
+ results.append(res)
115
+ return results
116
+
117
+
118
+ def create_reminders(outlook: OutlookClient, chosen: list[dict], *, at: str, duration: int,
119
+ reminder_minutes: int, on: str | None, show_as: str, dry_run: bool,
120
+ include_past: bool = False) -> list[dict]:
121
+ hh, mm = (int(x) for x in at.split(":"))
122
+ results = []
123
+ for r in chosen:
124
+ day = date.fromisoformat(on or r["due"] or "")
125
+ start = datetime(day.year, day.month, day.day, hh, mm)
126
+ subject = f"Planner: {r['title']}"
127
+ res = {"taskId": r["id"], "title": r["title"], "subject": subject, "start": start.isoformat()}
128
+ if start < datetime.now() and not include_past:
129
+ res["status"] = "skipped (date in the past)"
130
+ elif outlook.find_by_subject(day, subject):
131
+ res["status"] = "skipped (already exists)"
132
+ elif dry_run:
133
+ res["status"] = "dry-run"
134
+ else:
135
+ link = planner_task_url(r["planId"], r["id"], r["tenantId"])
136
+ outlook.create_event(subject, reminder_body(r["task"], r["plan"], link), start, duration,
137
+ reminder_minutes, show_as)
138
+ res["status"] = "created"
139
+ results.append(res)
140
+ return results
@@ -0,0 +1,77 @@
1
+ ---
2
+ name: dvm-planner
3
+ description: Read Microsoft Planner plans, buckets and tasks (including tasks assigned to me, assignees, due dates, checklists) as JSON using the dvm-planner CLI, which drives a signed-in Edge browser over CDP. Use when asked to list planners/plans, list or analyse Planner tasks, find tasks by assignee or due date, or export Planner data.
4
+ ---
5
+
6
+ # dvm-planner
7
+
8
+ `dvm-planner` exports Microsoft Planner data as JSON. It starts Edge with a remote-debugging port
9
+ (default 19222, profile `~/.dvm-planner/edge-profile`), reads the bearer token the Planner web UI
10
+ uses, and calls the Planner `taskapi` directly. The user must be signed in to Planner in that Edge
11
+ profile (SSO normally works automatically; otherwise ask them to sign in once in the launched window).
12
+
13
+ ## Commands (run with `uvx dvm-planner ...`)
14
+
15
+ | Goal | Command |
16
+ |---|---|
17
+ | Start Edge with CDP | `uvx dvm-planner launch` |
18
+ | List plans (recent + favorite) | `uvx dvm-planner plans [-o plans.json]` |
19
+ | Tasks assigned to me, by plan | `uvx dvm-planner mytasks [--summary] [-o file]` |
20
+ | Tasks assigned to someone else | `uvx dvm-planner usertasks "<name or e-mail>" [--with-due] [--plan <id/URL>] [-o file]` |
21
+ | Buckets + tasks of a plan | `uvx dvm-planner tasks <planId or Planner URL> [-o file]` |
22
+ | Every listed plan | `uvx dvm-planner tasks --all -o all.json` |
23
+ | Update a task | `uvx dvm-planner update-task <taskId or title fragment> [--due YYYY-MM-DD\|none] [--notes HTML] [--add-checklist TEXT] [--comment TEXT] [--patch JSON]` |
24
+
25
+ | List candidate tasks for reminders | `uvx dvm-planner remind --list [--json]` |
26
+ | Create Outlook reminders | `uvx dvm-planner remind (--all \| --select 1,3-5 \| --task <id/title>)... [--at HH:MM] [--duration 30] [--reminder-minutes 1440] [--on YYYY-MM-DD] [--show-as Busy] [--dry-run]` |
27
+ | Re-date reminders after due dates changed | `uvx dvm-planner remind --sync [--dry-run]` |
28
+
29
+ Global options: `--port`, `--profile`, `--edge-path`.
30
+
31
+ ## Calendar reminders (creates real calendar events)
32
+ `remind` makes an Outlook event `Planner: <task title>` on each task's due date (default 09:00, 30 min,
33
+ reminder 1 day before, body has plan, bucket and a task link). Never prompts when stdin is not a TTY:
34
+ 1. `remind --list --json` (my tasks, not complete, with due date; `n` is stable, sorted by due date).
35
+ 2. Confirm the selection with the user, run once with `--dry-run`, then run without it with
36
+ `--all`, `--select`, or `--task`. Past dates and events that already exist are skipped (idempotent).
37
+ 3. Needs an Outlook calendar tab signed in in the same Edge profile (opened automatically).
38
+ Tasks without a due date need `--include-no-due --on YYYY-MM-DD`.
39
+ After changing a task's due date (e.g. with `update-task --due`), run `remind --sync --dry-run` then `remind --sync`:
40
+ each `Planner: <title>` event whose date differs from the due date is moved (same time and duration).
41
+
42
+ `usertasks` resolves the person via Microsoft Graph (errors listing candidates if the name is
43
+ ambiguous; then retry with the e-mail). Planner has no per-user endpoint for other people, so it scans
44
+ recent/favorite plans plus plans holding your own tasks; use `--plan` to scan specific plans.
45
+
46
+ ## Updating tasks (writes change real data)
47
+ 1. Identify the exact task first (`mytasks`/`usertasks`/`tasks`) and show the user the task, plan and
48
+ the change. Get confirmation before writing unless the user's request was already explicit.
49
+ 2. Run `update-task`. A title fragment must match exactly one of *my* tasks, otherwise pass the task id.
50
+ `update-task` prints the updated task; verify the change in that output.
51
+ 3. Typical edits:
52
+ - Due date: `--due 2026-12-31` (clear with `--due none`). Stored as `dueDateTime.date`.
53
+ - Notes: `--notes "<div>html</div>"` replaces the whole description.
54
+ - Checklist: `--add-checklist "text"` (repeatable).
55
+ - Comment: `--comment "text"` posts to the task conversation.
56
+ 4. For anything else (title, percent complete, assignees, bucket, labels, start date) use `--patch` with the raw
57
+ JSON body the Planner UI sends, e.g. `--patch '{"dueDateTime":{"date":"2026-12-31"}}'`. If you don't know the
58
+ body, capture it: attach CDP to the Planner tab (`Network.enable`), have the user perform the action once in
59
+ the UI, and read the non-GET requests to `api.planner.svc.cloud.microsoft` (`request.postData`).
60
+ Details and examples: `docs/planner-cdp.md` section 5. Do not guess field names: unknown fields can return 200
61
+ yet change nothing (e.g. `dueUtcDateTime` is ignored on write), so always re-read the task to confirm.
62
+ 5. Writes need the task's current ETag (`If-Match`) and `OData-Version: 4.01`; the tool handles both. An HTTP
63
+ 412 means the task changed meanwhile; re-run.
64
+
65
+ ## Workflow
66
+ 1. Run the command, preferably with `-o file.json`, then filter the JSON with Python/jq rather than printing it all.
67
+ 2. Plan id is the segment after `/plan/` in a Planner URL.
68
+ 3. Task fields: `displayName`, `bucketId`, `percentComplete` (0/50/100), `status`, `priority`,
69
+ `startDateTime`, `dueDateTime` (`.date`; null when unset), `notes`, `checklist`, `links`,
70
+ `userAssignments` (list of `{id}` = Entra user object id without dashes), `customFieldValues`, `planView.appliedCategoryIds`.
71
+ 4. To filter by person: run `usertasks "<name>"` (resolves the user via Graph and filters `userAssignments`).
72
+ For custom logic, resolve the name to an object id (Graph `/users?$search="displayName:..."`,
73
+ header `ConsistencyLevel: eventual`) and match against `userAssignments[].id` (strip dashes).
74
+ 5. Always report when `dueDateTime` is empty instead of inventing dates. `plans` only covers
75
+ recent/favorite plans, so say so when answering "all plans".
76
+
77
+ Tokens last ~1h and are recaptured on each run.